Join query problem

Hi all,
I'm new to Berkeley DB and apologise if the answer to my question has been covered elsewhere.
I've been using the 'Getting Started Guide' (BerkeleyDB-Core-Cxx-GSG.pdf) to familiarise myself with the C++ API. The document has been vastly useful, but it has left me stranded on the subject of join queries. I have used the example in the guide (p 57) carefully to construct my join query between two secondary databases, but I get a segmentation fault that doesn't seem to originate from within my code. The GDB backtrace shows:
(gdb) backtrace
#0 0x007fbffb in __db_c_count () from /nfs/acari/dta/bdb/lib/libdb_cxx-4.4.so
#1 0x00807aef in __db_join_cmp () from /nfs/acari/dta/bdb/lib/libdb_cxx-4.4.so
#2 0x0013c1af in msort_with_tmp () from /lib/libc.so.6
#3 0x0013c0a7 in msort_with_tmp () from /lib/libc.so.6
#4 0x0013c360 in qsort () from /lib/libc.so.6
#5 0x00806de6 in __db_join () from /nfs/acari/dta/bdb/lib/libdb_cxx-4.4.so
#6 0x00804384 in __db_join_pp () from /nfs/acari/dta/bdb/lib/libdb_cxx-4.4.so
#7 0x0079070b in Db::join () from /nfs/acari/dta/bdb/lib/libdb_cxx-4.4.so
#8 0x0804a9fe in show_join ()
#9 0x0804a165 in main ()
The code that I have written to perform the join query looks like:
int show_join(MyDb &itemnameSDB, MyDb &catnameSDB,
     std::string &itemName, std::string &categoryName)
std::cout << "Have item : " << itemName << " and category : "
     << categoryName << std::endl;
// Position cursor at item
int ret;
Dbc *item_curs;
Dbt key, data;
try {
itemnameSDB.getDb().cursor(NULL, &item_curs, 0);
char * c_item = (char *)itemName.c_str();
key.set_data(c_item);
key.set_size(strlen(c_item) + 1);
if ((ret = item_curs->get(&key, &data, DB_SET)) != 0)
     std::cout << "Did not find any records matching item ["
          << c_item << "]" << std::endl;
catch(DbException &e) {        
itemnameSDB.getDb().err(e.get_errno(), "Error!");
} catch(std::exception &e) {
itemnameSDB.getDb().errx("Error! %s", e.what());
// Position cursor at category
Dbc *category_curs;
try {
catnameSDB.getDb().cursor(NULL, &category_curs, 0);
char c_category = (char )categoryName.c_str();
key.set_data(c_category);
key.set_size(strlen(c_category) + 1);
if ((ret = category_curs->get(&key, &data, DB_SET)) != 0)
     std::cout << "Did not find any records matching category ["
          << c_category << "]" << std::endl;
catch(DbException &e) {        
catnameSDB.getDb().err(e.get_errno(), "Error!");
} catch(std::exception &e) {
catnameSDB.getDb().errx("Error! %s", e.what());
// Set up an array of cursors ready for the join
Dbc *carray[3];
carray[0] = item_curs;
carray[1] = category_curs;
carray[3] = NULL;
// Perform the join
Dbc *join_curs;
try {
if ((ret = itemnameSDB.getDb().join(carray, &join_curs, 0)) != 0)
     std::cout << "Successful query results should go here." << std::endl;
catch(DbException &e) {        
itemnameSDB.getDb().err(e.get_errno(), "Error!");
} catch(std::exception &e) {
itemnameSDB.getDb().errx("Error! %s", e.what());
// Iterate through results using the join cursor
while ((ret = join_curs->get(&key, &data, 0)) == 0)
std::cout << "Iterating through cursors" << std::endl;
// If we exited the loop because we ran out of records,
// then it has completed successfully.
if (ret == DB_NOTFOUND)
item_curs->close();
category_curs->close();
join_curs->close();
return(0);
The seg fault occurs at the line in the final try/catch block where the Db.join() call is made.
It seems highly likely that I am making a simple mistake due to inexperience (both with Berkeley DB and C++) and am hoping that the problem glares out at someone with deeper knowledge.
I'm running this under linux if this makes any difference.
Many thanks for reading this far,
Dan

Hi Keith,
The following test program isn't pretty, but should produce the seg fault that I'm seeing. Much of the code is copy-and-pasted from the C++ API guide. It will need some input data to run - and presumably create the correct error. Save the following as ./small_inventory.txt (this is also just hacked from the guide):
Oranges#OranfruiRu6Ghr#0.71#451#fruits#TriCounty Produce
Spinach#SpinvegeVcqXL6#0.11#708#vegetables#TriCounty Produce
Banana Split#Banadessfif758#11.07#14#desserts#The Baking Pan
Thanks for your help,
Dan
Code follows:
#include <db_cxx.h>
#include <iostream>
#include <fstream>
#include <cstdlib>
class InventoryData
public:
inline void setPrice(double price) {price_ = price;}
inline void setQuantity(long quantity) {quantity_ = quantity;}
inline void setCategory(std::string &category) {category_ = category;}
inline void setName(std::string &name) {name_ = name;}
inline void setVendor(std::string &vendor) {vendor_ = vendor;}
inline void setSKU(std::string &sku) {sku_ = sku;}
inline double& getPrice() {return(price_);}
inline long& getQuantity() {return(quantity_);}
inline std::string& getCategory() {return(category_);}
inline std::string& getName() {return(name_);}
inline std::string& getVendor() {return(vendor_);}
inline std::string& getSKU() {return(sku_);}
/* Initialize our data members */
void clear()
price_ = 0.0;
quantity_ = 0;
category_ = "";
name_ = "";
vendor_ = "";
sku_ = "";
// Default constructor
InventoryData() { clear(); }
// Constructor from a void *
// For use with the data returned from a bdb get
InventoryData(void *buffer)
char buf = (char )buffer;
price_ = *((double *)buf);
bufLen_ = sizeof(double);
quantity_ = *((long *)(buf + bufLen_));
bufLen_ += sizeof(long);
name_ = buf + bufLen_;
bufLen_ += name_.size() + 1;
sku_ = buf + bufLen_;
bufLen_ += sku_.size() + 1;
category_ = buf + bufLen_;
bufLen_ += category_.size() + 1;
vendor_ = buf + bufLen_;
bufLen_ += vendor_.size() + 1;
* Marshalls this classes data members into a single
* contiguous memory location for the purpose of storing
* the data in a database.
char *
getBuffer()
// Zero out the buffer
memset(databuf_, 0, 500);
* Now pack the data into a single contiguous memory location for
* storage.
bufLen_ = 0;
int dataLen = 0;
     dataLen = sizeof(double);
     memcpy(databuf_, &price_, dataLen);
     bufLen_ += dataLen;
     dataLen = sizeof(long);
     memcpy(databuf_ + bufLen_, &quantity_, dataLen);
     bufLen_ += dataLen;
packString(databuf_, name_);
packString(databuf_, sku_);
packString(databuf_, category_);
packString(databuf_, vendor_);
return (databuf_);
* Returns the size of the buffer. Used for storing
* the buffer in a database.
inline size_t getBufferSize() { return (bufLen_); }
/* Utility function used to show the contents of this class */
void
show() {
std::cout << "\nName: " << name_ << std::endl;
std::cout << " SKU: " << sku_ << std::endl;
std::cout << " Price: " << price_ << std::endl;
std::cout << " Quantity: " << quantity_ << std::endl;
std::cout << " Category: " << category_ << std::endl;
std::cout << " Vendor: " << vendor_ << std::endl;
private:
* Utility function that appends a char * to the end of
* the buffer.
void
packString(char *buffer, std::string &theString)
size_t string_size = theString.size() + 1;
memcpy(buffer+bufLen_, theString.c_str(), string_size);
bufLen_ += string_size;
/* Data members */
std::string category_, name_, vendor_, sku_;
double price_;
long quantity_;
size_t bufLen_;
char databuf_[500];
//Forward declarations
void loadDB(Db &, std::string &);
int get_item_name(Db dbp, const Dbt pkey, const Dbt pdata, Dbt skey);
int get_category_name(Db dbp, const Dbt pkey, const Dbt pdata, Dbt skey);
int show_join(Db &item_index, Db &category_index,
     std::string &itemName, std::string &categoryName);
int main (){
Db primary_database(NULL, 0); // Primary
Db item_index(NULL, 0); // Secondary
Db category_index(NULL, 0); // Secondary
// Open the primary database
primary_database.open(NULL,
               "inventorydb.db",
               NULL,
               DB_BTREE,
               DB_CREATE,
               0);
/* // Setup the secondary to use sorted duplicates.
// This is often desireable for secondary databases.
item_index.set_flags(DB_DUPSORT);
category_index.set_flags(DB_DUPSORT);
// Open secondary databases
item_index.open(NULL,
          "itemname.sdb",
          NULL,
          DB_BTREE,
          DB_CREATE,
          0);
category_index.open(NULL,
          "categoryname.sdb",
          NULL,
          DB_BTREE,
          DB_CREATE,
          0);
// Associate the primary and the secondary dbs
primary_database.associate(NULL,
               &item_index,
               get_item_name,
               0);
primary_database.associate(NULL,
               &category_index,
               get_category_name,
               0);
// Load database
std::string input_file = "./small_inventory.txt";
try {
loadDB(primary_database, input_file);
} catch(DbException &e) {
std::cerr << "Error loading databases. " << std::endl;
std::cerr << e.what() << std::endl;
return (e.get_errno());
} catch(std::exception &e) {
std::cerr << "Error loading databases. " << std::endl;
std::cerr << e.what() << std::endl;
return (-1);
// Perform join query
std::string itemName = "Spinach";
std::string categoryName = "vegetables";
show_join(item_index, category_index, itemName, categoryName);
// Close dbs
item_index.close(0);
category_index.close(0);
primary_database.close(0);
return(0);
} // End main
// Used to locate the first pound sign (a field delimiter)
// in the input string.
size_t
getNextPound(std::string &theString, std::string &substring)
size_t pos = theString.find("#");
substring.assign(theString, 0, pos);
theString.assign(theString, pos + 1, theString.size());
return (pos);
// Loads the contents of the inventory.txt file into a database
void
loadDB(Db &inventoryDB, std::string &inventoryFile)
InventoryData inventoryData;
std::string substring;
size_t nextPound;
std::ifstream inFile(inventoryFile.c_str(), std::ios::in);
if ( !inFile )
std::cerr << "Could not open file '" << inventoryFile
<< "'. Giving up." << std::endl;
throw std::exception();
while (!inFile.eof())
inventoryData.clear();
std::string stringBuf;
std::getline(inFile, stringBuf);
// Now parse the line
if (!stringBuf.empty())
nextPound = getNextPound(stringBuf, substring);
inventoryData.setName(substring);
nextPound = getNextPound(stringBuf, substring);
inventoryData.setSKU(substring);
nextPound = getNextPound(stringBuf, substring);
inventoryData.setPrice(strtod(substring.c_str(), 0));
nextPound = getNextPound(stringBuf, substring);
inventoryData.setQuantity(strtol(substring.c_str(), 0, 10));
nextPound = getNextPound(stringBuf, substring);
inventoryData.setCategory(substring);
nextPound = getNextPound(stringBuf, substring);
inventoryData.setVendor(substring);
void buff = (void )inventoryData.getSKU().c_str();
size_t size = inventoryData.getSKU().size()+1;
Dbt key(buff, (u_int32_t)size);
buff = inventoryData.getBuffer();
size = inventoryData.getBufferSize();
Dbt data(buff, (u_int32_t)size);
inventoryDB.put(NULL, &key, &data, 0);
inFile.close();
int
get_item_name(Db dbp, const Dbt pkey, const Dbt pdata, Dbt skey)
* First, obtain the buffer location where we placed the item's name. In
* this example, the item's name is located in the primary data. It is the
* first string in the buffer after the price (a double) and the quantity
* (a long).
u_int32_t offset = sizeof(double) + sizeof(long);
char itemname = (char )pdata->get_data() + offset;
// unused
(void)pkey;
* If the offset is beyond the end of the data, then there was a problem
* with the buffer contained in pdata, or there's a programming error in
* how the buffer is marshalled/unmarshalled. This should never happen!
if (offset > pdata->get_size()) {
dbp->errx("get_item_name: buffer sizes do not match!");
// When we return non-zero, the index record is not added/updated.
return (-1);
/* Now set the secondary key's data to be the item name */
skey->set_data(itemname);
skey->set_size((u_int32_t)strlen(itemname) + 1);
return (0);
int
get_category_name(Db dbp, const Dbt pkey, const Dbt pdata, Dbt skey)
* First, obtain the buffer location where we placed the item's name. In
* this example, the item's name is located in the primary data. It is the
* first string in the buffer after the price (a double) and the quantity
* (a long).
u_int32_t offset = sizeof(double) + sizeof(long);
char itemname = (char )pdata->get_data() + offset;
offset += strlen(itemname) + 1;
char sku = (char )pdata->get_data() + offset;
offset += strlen(sku) + 1;
char category = (char )pdata->get_data() + offset;
// unused
(void)pkey;
* If the offset is beyond the end of the data, then there was a problem
* with the buffer contained in pdata, or there's a programming error in
* how the buffer is marshalled/unmarshalled. This should never happen!
if (offset > pdata->get_size()) {
dbp->errx("get_item_name: buffer sizes do not match!");
// When we return non-zero, the index record is not added/updated.
return (-1);
/* Now set the secondary key's data to be the item name */
skey->set_data(category);
skey->set_size((u_int32_t)strlen(category) + 1);
return (0);
int
show_join(Db &itemnameSDB, Db &catnameSDB,
     std::string &itemName, std::string &categoryName)
std::cout << "Have item : " << itemName << " and category : "
     << categoryName << std::endl;
// Position cursor at item
int ret;
Dbc *item_curs;
Dbt key, data;
try {
itemnameSDB.cursor(NULL, &item_curs, 0);
char * c_item = (char *)itemName.c_str();
key.set_data(c_item);
key.set_size(strlen(c_item) + 1);
if ((ret = item_curs->get(&key, &data, DB_SET)) != 0)
     std::cout << "Did not find any records matching item ["
          << c_item << "]" << std::endl;
// while (ret != DB_NOTFOUND)
//      printf("Database record --\n");
//     std::cout << "Key : " << (char *)key.get_data() << std::endl;
//      ret = item_curs->get(&key, &data, DB_NEXT_DUP);
catch(DbException &e) {        
itemnameSDB.err(e.get_errno(), "Error!");
} catch(std::exception &e) {
itemnameSDB.errx("Error! %s", e.what());
// Position cursor at category
Dbc *category_curs;
try {
catnameSDB.cursor(NULL, &category_curs, 0);
char c_category = (char )categoryName.c_str();
key.set_data(c_category);
key.set_size(strlen(c_category) + 1);
if ((ret = category_curs->get(&key, &data, DB_SET)) != 0)
     std::cout << "Did not find any records matching category ["
          << c_category << "]" << std::endl;
//!! Debug, print everything
// Dbt temp_key, temp_data;
// while ((ret = category_curs->get(&temp_key, &temp_data, DB_NEXT)) == 0) {        
// std::cout << "Key : " << (char *)temp_key.get_data() << std::endl;
catch(DbException &e) {        
catnameSDB.err(e.get_errno(), "Error!");
} catch(std::exception &e) {
catnameSDB.errx("Error! %s", e.what());
// Set up an array of cursors ready for the join
Dbc *carray[3];
carray[0] = item_curs;
carray[1] = category_curs;
carray[3] = NULL;
// Perform the join
Dbc *join_curs;
try {
if ((ret = itemnameSDB.join(carray, &join_curs, 0)) != 0)
     std::cout << "Successful query results should go here." << std::endl;
catch(DbException &e) {        
itemnameSDB.err(e.get_errno(), "Error[3]!");
} catch(std::exception &e) {
itemnameSDB.errx("Error! %s", e.what());
// Iterate through results using the join cursor
while ((ret = join_curs->get(&key, &data, 0)) == 0)
std::cout << "Iterating through cursors" << std::endl;
// If we exited the loop because we ran out of records,
// then it has completed successfully.
if (ret == DB_NOTFOUND)
item_curs->close();
category_curs->close();
join_curs->close();
return(0);
}

Similar Messages

  • Problem getting results with no unique key in a joined query

    I created a descriptor to do a joined query, which generated a query in log as:
    Select t0.empID,t1.empID, t1.phone from Emp t0, Phone t1
    where t0.empId=t1.empId and t0.empId=1001
    When I run it, I got the result as:
    1001,1001,9999999
    1001,1001,9999999
    The correct result should be (I copy and paste the query from log into SQL-Plus):
    1001,1001,9999999
    1001,1001,1234455
    I suspect this is caused by Toplink caching objects by primary key. I wonder if anybody has a solution for this.
    My descriptor is created using WorkBench. Emp is the primary table, Phone as additional table linked by foreignKey empId.
    The join is implemented by modifying the descriptor as the following:
    ExpressionBuilder builder = new ExpressionBuilder();
    descriptor.getQueryManage()
    .setMultipleTableJoinExpression(
    builder.getField("EMP.EMPID").equal(
    builder.getField("EMP.EMPID")));
    descriptor.disableCacheHits();
    I'd really appreciate your help.

    I am implementing a people search function. The batch reading is quite expensive if toplink does a read query for every person. A customized query requires only one database access, the other way may requires hundreds.
    I don't want to use the cache either in this case because the database is also accessed by legacy system which cann't notify toplink any updates.
    I opened a TAR on this and the solution I got is to use ReportQuery rathen than ReadAllQuery. The only problem here is that now I have to map the query result to my class manually.

  • Deciphering column names in a join query using jdbc

    hi all....
    I am making a database adapter for a generic report generater. This adapter would be forming queries involing various tables. There are two ways of doing it . I fire an sql on parent table to get the keys and then go to child table for each one of them or i form a join query to get desired result.
    i want to go with the later approach where my query would be forming a join. The problem comes when table involved in this join has columns with the same name. for eg if a column "NOTE" is there in table A as well as table B on which i have a join. Resultset returns me with two "NOTE" columns and i cannot recognize which one belongs to which table.
    all API calls including getString("Note") seems to be referring to the first occurence of "Note" column.
    Also getTableName() and getSchemaName() APIs on resultsetMetadata doesnt return in anything in case of joins.
    Any pointers would be most appreciated.
    cheers
    vivek

    thanks for suggesting this solution ... though i had thought of the same onece .... unfortunately i cannot implement something like this coz out of the result set i have to instantiate an object hierarchy depending on the schema ....
    this also puts me in a doubt whether i can use join in my case.
    for eg ... .
    lets say we have a customer talbe and and address table which has one to many relationship .... one contact can have multiple addresses.
    Assuming a contanct "Joe Bloggs" having 3 addresses ...a query like following
    select contact.firstname contactfirstname , address.streetname addressstreetname from contact , address where contact.contactid = address.contactid
    this would return me 3 rows and i can also recognize various columns with their aliases ..
    but i would lose an important fact that i have to create one java object for contact class and 3 instances for addresses which i have to return finally.
    this means that i would like to return an object hierarchy with one contact object and 3 address object underneath it linked with contactid.
    Any other suggestions after reading the complete requirement are most welcome ...sorry for not puting the entire thing at first.
    i guess the only soln left is to visit contact and address table separately. :(

  • Filter on "---" in Left Outer Join Query

    Hi guys,
    very basic question but I have not found an answer, yet. I built an left outer join MDO query and need to select all those dataset that did not find a "partner", that is fields are set to "---". However, I do not manage to filter on '---', NULL...
    When using SQL, it appears to be a String "---" but in MDO???

    Hey guys, found out that IS NULL needs to be used in query. Anyway, it appears to cause problems somewhere else.
    I placed an IS NULL filter expression inside a join query but query did not return any results when called in by transaction. After removing this line, both NULL and NOT NULL data were returned. When used in test mode, IS NULL was working fine...

  • Left outer join query

    Hi Experts,
        I am facing a problem with left outer join query. Am using one standard table and ztable for this join. My problem is values are not extracted from the Ztable.
    Query:
          SELECT  b~lifnr b~belnr b~gjahr b~xblnr b~shkzg b~blart b~zfbdt b~budat b~wrbtr
             b~wskto b~zlspr s~EXTRACT_STATUS s~maturity_date FROM bsik AS b
             LEFT OUTER JOIN zprm_rvne_sapdoc AS s
             ON s~belnr  EQ  b~belnr
             AND s~gjahr EQ b~gjahr
             INTO CORRESPONDING FIELDS OF TABLE it_join
                WHERE b~zlsch = p_zlsch
                AND b~xblnr IN so_invno
                ORDER BY b~lifnr b~xblnr.
    I have all entries of BSIK table in Ztable with extract status as Y but this query is not fetching extract status and maturity date of ztable so it is blank in the internal table.
    Need solution.
    Regards
    Sridevi S

    Hi,
    see the sample wiki for writing the Left outer join
    http://wiki.sdn.sap.com/wiki/display/Snippets/EmployeeInfotype0000to9999ChangeHistory
    Specifying Two or More Database Tables as a Left Outer Join
    The left outer join, on the other hand, reads lines from the left-hand database table or join even if there is no corresponding line in the right-hand table.
    SELECT...
      FROM <tab> LEFT [OUTER] JOIN <dbtab> [AS <alias>] ON <cond>
           <options>
    <tab> and <dbtab> are subject to the same rules and conditions as in an inner join. The OUTER addition is optional. The tables are linked in the same way as the inner join with the one exception that all lines selected from <tab> are included in the final selection. If <dbtab> does not contain any lines that meet the condition <cond>, the system includes a single line in the selection whose columns from <dbtab> are filled with null values.
    In the left outer join, more restrictions apply to the condition <cond> than in the inner join. In addition to the above restrictions:
    EQ or = is the only permitted relational operator.
    There must be at least one comparison between columns from <tab> and <dbtab>.
    The WHERE clause may not contain any comparisons with columns from <dbtab>. All comparisons using columns from <dbtab> must appear in the condition <cond>.
    If we have two tables named stud1,stud2 with the following data
    Stud1: id Name stud2: id Name
    1 xxx 1 aaa
    2 yyy 2 bbb
    3 zzz 4 ccc
    4 www 6 ddd
    When we use Left Outer Join we get the output as:
    1 aaa
    2 bbb
    3 <Null>
    4 ccc
    When we use Right Outer Join we get the output as:
    1 aaa
    2 bbb
    4 ccc
    <Null> ddd
    When we use Full Outer Join we get the output as:
    1 aaa
    2 bbb
    3 <Null>
    4 ccc
    <Null> ddd
    Prabhudas

  • Cartesian Join query optimization

    Hello Experts!
    I have a question about cartesian join query which might look a bit weird.
    Assume the SQL query like that:
    SELECT DISTINCT A.NAME
    FROM A, B, C;
    Here we have cartesian join for 3 tables A, B and C.
    It looks to me, in order to get the result for such a particular SQL tables/sets B and C need to be accessed only to ensure they return at least 1 row (otherwise result set is empty), query table A, but there is no actual need to join the data.
    If you run such a query Oracle is doing full table scans and actually joins the data.
    Yes, DBMS is doing exactly what you are asking for, but I wonder if there is any way (SQL hint or db parameter or anything else) to enforce more optimal access path here?
    Obvious solution to remove B and C tables from the SELECT statement is not acceptable. :-)
    Thank you!

    Your statement in the other thread indicates you don't understand how the BI prompts actually work because you say you want it to do something that doesn't make sense for it to do.
    Of course Product and Account levels will be constrained to the interval you specified. It wouldn't make sense for them not to be. Because that would mean returning data for based on product and account levels that has a different open data range than what you specified.
    All UI prompt dialogs I have seen use AND relationships between the parameters. If there are three parameters (A, B, C) then the ultimate relationship is 'A AND B AND C'; not 'A OR (B AND C)', 'A AND (B OR C)', 'A OR (B OR C).
    Unless the tool allows you to select OR relationships you need to use a separate dialog box (parameter dialog) for each condition set.:-)
    I understand how BI prompts work and basically agree on your comment, but there are two problems here:
    1. I need to convince the customer his original requirements are not valid. Customer want it to work different way and there are some reasons why.
    2. There are pretty large dimensions and fact tables used here, so when I choose filter criteria for the Product (which is small table) to populate/recalculate prompt values, large SR dimension and fact tables are joined too, and if there are Account dimension filters added, huge Account dimension will be added as well. This looks to be a bit sub-optimal for just populating the Product prompt values.
    Of course, technically this is solvable, but requires to put some extra effort and does not solve the 1st issue.
    That other link doesn't explain the sample code you posted in this thread. Post the actual query that is being generated and the query that you want to actually use.This is what is generated:
    >
    select distinct T311691.X_CUST_SUBTYPE as c1
    from
    WC_LOV_SR_AREA_H T311695,
    WC_LOV_PROD_H T311687,
    WC_LOV_CUST_TYPE_H T311691,
    W_SRVREQ_D T302384 /* Dim_W_SRVREQ_D */
    where ( T311687.LEV1 = 'Product X' and T311691.X_CUST_TYPE = 'Business' and T302384.OPEN_DT between TO_DATE('2012-03-01 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') and TO_DATE('2012-03-31 00:00:00' , 'YYYY-MM-DD HH24:MI:SS') )
    order by c1
    >
    This is what is actually needed to query this data:
    >
    select distinct T311691.X_CUST_SUBTYPE as c1
    from
    WC_LOV_CUST_TYPE_H T311691
    where ( T311691.X_CUST_TYPE = 'Business' )
    order by c1

  • SQL+-MULTI TABLE QUERY PROBLEM

    HAI ALL,
    ANY SUGGESTION PLEASE?
    SUB: SQL+-MULTI TABLE QUERY PROBLEM
    SQL+ QUERY GIVEN:
    SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
    HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
    DLC_POLYMORPHS_NORMAL_VALUE FROM PATIENTS_MASTER1, HAEMATOLOGY1,
    DIFFERENTIAL_LEUCOCYTE_COUNT1
    WHERE PATIENT_NUM = HMTLY_PATIENT_NUM AND PATIENT_NUM = DLC_PATIENT_NUM AND PATIENT_NUM
    = &PATIENT_NUM;
    RESULT GOT:
    &PATIENT_NUM =1
    no rows selected
    &PATIENT_NUM=2
    no rows selected
    &PATIENT_NUM=3
    PATIENT_NUM 3
    PATIENT_NAME KKKK
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 4
    HMTLY_RBC_NORMAL 4.6-6.0
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     60
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    ACTUAL WILL BE:
    &PATIENT_NUM=1
    PATIENT_NUM 1
    PATIENT_NAME BBBB
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 5
    HMTLY_RBC_NORMAL 4.6-6.0
    &PATIENT_NUM=2
    PATIENT_NUM 2
    PATIENT_NAME GGGG
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     42
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    &PATIENT_NUM=3
    PATIENT_NUM 3
    PATIENT_NAME KKKK
    HMTLY_TEST_NAME HAEMATOLOGY
    HMTLY_RBC_VALUE 4
    HMTLY_RBC_NORMAL 4.6-6.0
    DLC_TEST_NAME DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE     60
    DLC_POLYMORPHS_NORMAL_VALUE     40-65
    4 TABLES FOR CLINICAL LAB FOR INPUT DATA AND GET REPORT ONLY FOR TESTS MADE FOR PARTICULAR
    PATIENT.
    TABLE1:PATIENTS_MASTER1
    COLUMNS:PATIENT_NUM, PATIENT_NAME,
    VALUES:
    PATIENT_NUM
    1
    2
    3
    4
    PATIENT_NAME
    BBBB
    GGGG
    KKKK
    PPPP
    TABLE2:TESTS_MASTER1
    COLUMNS:TEST_NUM, TEST_NAME
    VALUES:
    TEST_NUM
    1
    2
    TEST_NAME
    HAEMATOLOGY
    DIFFERENTIAL LEUCOCYTE COUNT
    TABLE3:HAEMATOLOGY1
    COLUMNS:
    HMTLY_NUM,HMTLY_PATIENT_NUM,HMTLY_TEST_NAME,HMTLY_RBC_VALUE,HMTLY_RBC_NORMAL_VALUE     
    VALUES:
    HMTLY_NUM
    1
    2
    HMTLY_PATIENT_NUM
    1
    3
    MTLY_TEST_NAME
    HAEMATOLOGY
    HAEMATOLOGY
    HMTLY_RBC_VALUE
    5
    4
    HMTLY_RBC_NORMAL_VALUE
    4.6-6.0
    4.6-6.0
    TABLE4:DIFFERENTIAL_LEUCOCYTE_COUNT1
    COLUMNS:DLC_NUM,DLC_PATIENT_NUM,DLC_TEST_NAME,DLC_POLYMORPHS_VALUE,DLC_POLYMORPHS_
    NORMAL_VALUE,
    VALUES:
    DLC_NUM
    1
    2
    DLC_PATIENT_NUM
    2
    3
    DLC_TEST_NAME
    DIFFERENTIAL LEUCOCYTE COUNT
    DIFFERENTIAL LEUCOCYTE COUNT
    DLC_POLYMORPHS_VALUE
    42
    60
    DLC_POLYMORPHS_NORMAL_VALUE
    40-65
    40-65
    THANKS
    RCS
    E-MAIL:[email protected]
    --------

    I think you want an OUTER JOIN
    SELECT PATIENT_NUM, PATIENT_NAME, HMTLY_TEST_NAME, HMTLY_RBC_VALUE,
    HMTLY_RBC_NORMAL_VALUE, DLC_TEST_NAME, DLC_POLYMORPHS_VALUE,
    DLC_POLYMORPHS_NORMAL_VALUE
    FROM PATIENTS_MASTER1, HAEMATOLOGY1,  DIFFERENTIAL_LEUCOCYTE_COUNT1
    WHERE PATIENT_NUM = HMTLY_PATIENT_NUM (+)
    AND PATIENT_NUM = DLC_PATIENT_NUM (+)
    AND PATIENT_NUM = &PATIENT_NUM;Edited by: shoblock on Nov 5, 2008 12:17 PM
    outer join marks became stupid emoticons or something. attempting to fix

  • Join query with cfoutput group

    Hi,
    I have the problem with join query and output the goup by, can anyone helps please?
    1: worked fine
    <cfquery name="qOrgs" datasource="#GetDSN()#">
    select org
    from cat
    </cfquery>
    <cfoutput query="qOrgs" group="org">
    #org#<br />
    </cfoutput>
    2: not work, not grouping and display duplicated.
    <cfquery name="qOrgs" datasource="#GetDSN()#">
    select org
      from user u
      inner JOIN cat c
      on u.userid= c.userid
    </cfquery>
    <cfoutput query="qOrgs" group="org">
    #org#<br />
    </cfoutput>
    Thanks

    To expand on Dan's answer;
    The "group" property of the <cfoutput...> tag is fairly simplistic.  All it actuall does is conditionally output content whenever the value of the specified group column changes.
    So if you do not use an ORDER BY clause in your SQL to group the values of that column together (or they don't naturally group because of the current state of the data in the database) then the output is probably not going to be as desired.

  • Self-join query to Analytical function query

    Hi All,
    I have converted a self-join query to Analytical function query due to the performance reasons.
    Query which is using Analytical function is giving the correct count as I compared it with query using Self-Join. Can you please tell what is wrong in the query.
    ==========================
    Query using Self-Join
    select count(1)
    From (select t1.*, max(t1.dw_creation_dt) over (partition by t1.empl_id) pers_max_date
    from ohr_pers_curr t1 ) pers
         , (select t2.*, max(t2.dw_creation_dt) over (partition by t2.empl_id, t2.empl_rcd) job_max_date
         from OHR_JOB_CURR t2) job
    where pers.empl_id = job.empl_id
    and pers.dw_creation_dt=pers.pers_max_date
    and job.dw_creation_dt=job.job_max_date
    and job.dummy_row_flag = 'N'
    and pers.dw_creation_rsn_cd in ('N', 'U')
    and job.dw_creation_rsn_cd in ('N', 'U')
    ================================================
    Query Using Analytical function
    select count(1)
    From (select t1.*, max(t1.dw_creation_dt) over (partition by t1.empl_id) pers_max_date
    from ohr_pers_curr t1 ) pers
         , (select t2.*, max(t2.dw_creation_dt) over (partition by t2.empl_id, t2.empl_rcd) job_max_date
         from OHR_JOB_CURR t2) job
    where pers.empl_id = job.empl_id
    and pers.dw_creation_dt=pers.pers_max_date
    and job.dw_creation_dt=job.job_max_date
    and job.dummy_row_flag = 'N'
    and pers.dw_creation_rsn_cd in ('N', 'U')
    and job.dw_creation_rsn_cd in ('N', 'U')
    ==================================

    Hi David,
    The base is same but the problem is different.
    As far as implementation concern these queries looks same, but when I see there counts, they do not match. I do not have any reason why this happening.
    Regards
    Gaurav

  • Join query in a dynamic list of values query

    I have a join query in a dynamic list of values query. The value does not return a text value, but rather the id value.
    Is it possible to use a join query in a dynamic list of values query?
    For example...in the below query, I expect to see ename in the drop down list, but I see class_emp_id.
    select b.ename d, a.class_emp_id r
    from class_emp a, emp b
    where a.class_cat_id = :CURR_CLASS_CAT_ID
    and a.emp_id = b.emp_id
    order by 1
    Thanks,
    Reid

    :CURR_CLASS_CAT_ID is a number datatype.
    I think the problem is with the ARF. Whenever I change the dynamic LOV query to exclude the :CURR_CLASS_CAT_ID (a passed in session variable), the drop down shows all the text names I am looking for; albeit, too many since I am excluding the :CURR_CLASS_CAT_ID.
    The page I am having the problem with is a popup that is called from a report link on another page. When I show the session variables on the popup page, it shows values for only 1 of the 3 session variables I am passing to this page.
    I am using the javascript:popUp2 syntax when I call the popup page from the report link.
    As I said previously, I am passing 3 parms and only the 1st parm is getting a value. Yes, there are values for all three parms in the record of the report.
    Is there a limit to the number of variables (itemNames) that can be passed to the popup using this method?

  • Join query getting poor performance

    Hi,
    This is my join query to retriving data , i had a problem from this, its getting very slow to retrive data, even i used in report builder, it could not build the report.
    From this select statement i've using three tables ,
    please help and have suggestion to tune my query better fast and give some new idea , but i'm using oracle 8i.
    select a.customer_code customer, c.name name, c.place place, a.product_code product, b.quantity ord_qty, nvl(b.delivery_district_code,c.district_code) district, nvl(b.delivery_town_code,c.town_code) town
    from order_book a, order_book_detail b, customer c
    where a.region_code = b.region_code
    and a.order_book_form_no = b.order_book_form_no
    and a.customer_code = c.customer_code
    and c.division_code = 34
    and a.region_code = 10
    and c.state_code = 1
    and a.order_book_form_date = '18-OCT-2007'
    and nvl(c.classification_code,'N') = 'S'
    order by 1;
    regards
    venki

    why nobody answering me.Because you gave us nothing to investigate. Please read [url http://forums.oracle.com/forums/thread.jspa?threadID=501834&tstart=0]this thread and post a tkprof output here. For an explain plan in 8i, you could "set autotrace on explain" in SQL*Plus.
    Regards,
    Rob.

  • How to get Hierarchical XML File from a Database Join Query !

    Hi,
    How can i get a Hierarchical XML File from a Database Join Query ?
    Any join query returns repeated values as below:
    BD17:SQL>select d.dname, e.ename, e.sal
    2 from dept d
    3 natural join
    4 emp e
    5 /
    DNAME ENAME SAL
    ACCOUNTING CLARK 2450
    ACCOUNTING KING 5000
    ACCOUNTING MILLER 1300
    RESEARCH SMITH 800
    RESEARCH ADAMS 1100
    RESEARCH FORD 3000
    RESEARCH SCOTT 3000
    RESEARCH JONES 2975
    SALES ALLEN 1600
    SALES BLAKE 2850
    SALES MARTIN 1250
    SALES JAMES 950
    SALES TURNER 1500
    SALES WARD 1250
    14 rows selected.
    We tried use DBMS_XMLQUERY to generate a xml file, but it was unable to get xml in Hierarchical format.
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    - <ROWSET>
    - <ROW num="1">
    <DNAME>ACCOUNTING</DNAME>
    <ENAME>CLARK</ENAME>
    <SAL>2450</SAL>
    </ROW>
    - <ROW num="2">
    <DNAME>ACCOUNTING</DNAME>
    <ENAME>KING</ENAME>
    <SAL>5000</SAL>
    </ROW>
    - <ROW num="3">
    <DNAME>ACCOUNTING</DNAME>
    <ENAME>MILLER</ENAME>
    <SAL>1300</SAL>
    </ROW>
    - <ROW num="4">
    <DNAME>RESEARCH</DNAME>
    <ENAME>SMITH</ENAME>
    <SAL>800</SAL>
    </ROW>
    - <ROW num="5">
    <DNAME>RESEARCH</DNAME>
    <ENAME>ADAMS</ENAME>
    <SAL>1100</SAL>
    </ROW>
    - <ROW num="6">
    <DNAME>RESEARCH</DNAME>
    <ENAME>FORD</ENAME>
    <SAL>3000</SAL>
    </ROW>
    - <ROW num="7">
    <DNAME>RESEARCH</DNAME>
    <ENAME>SCOTT</ENAME>
    <SAL>3000</SAL>
    </ROW>
    - <ROW num="8">
    <DNAME>RESEARCH</DNAME>
    <ENAME>JONES</ENAME>
    <SAL>2975</SAL>
    </ROW>
    - <ROW num="9">
    <DNAME>SALES</DNAME>
    <ENAME>ALLEN</ENAME>
    <SAL>1600</SAL>
    </ROW>
    - <ROW num="10">
    <DNAME>SALES</DNAME>
    <ENAME>BLAKE</ENAME>
    <SAL>2850</SAL>
    </ROW>
    - <ROW num="11">
    <DNAME>SALES</DNAME>
    <ENAME>MARTIN</ENAME>
    <SAL>1250</SAL>
    </ROW>
    - <ROW num="12">
    <DNAME>SALES</DNAME>
    <ENAME>JAMES</ENAME>
    <SAL>950</SAL>
    </ROW>
    - <ROW num="13">
    <DNAME>SALES</DNAME>
    <ENAME>TURNER</ENAME>
    <SAL>1500</SAL>
    </ROW>
    - <ROW num="14">
    <DNAME>SALES</DNAME>
    <ENAME>WARD</ENAME>
    <SAL>1250</SAL>
    </ROW>
    </ROWSET>
    Thank you for some help.
    Nelson Alberti

    Hi,
    I wrote a general ABAP program which can be configured to grab contrent from an URL and post that content as a new PI message into the integration adapter .... from that point on normal PI configuration can be used to route it to anywhere ...
    It can be easily scheduled as a background job to grab content on a daily basis etc ...
    Regards,
    Steven

  • How can I perform this kind of range join query using DPL?

    How can I perform this kind of range join query using DPL?
    SELECT * from t where 1<=t.a<=2 and 3<=t.b<=5
    In this pdf : http://www.oracle.com/technology/products/berkeley-db/pdf/performing%20queries%20in%20oracle%20berkeley%20db%20java%20edition.pdf,
    It shows how to perform "Two equality-conditions query on a single primary database" just like SELECT * FROM tab WHERE col1 = A AND col2 = B using entity join class, but it does not give a solution about the range join query.

    I'm sorry, I think I've misled you. I suggested that you perform two queries and then take the intersection of the results. You could do this, but the solution to your query is much simpler. I'll correct my previous message.
    Your query is very simple to implement. You should perform the first part of query to get a cursor on the index for 'a' for the "1<=t.a<=2" part. Then simply iterate over that cursor, and process the entities where the "3<=t.b<=5" expression is true. You don't need a second index (on 'b') or another cursor.
    This is called "filtering" because you're iterating through entities that you obtain from one index, and selecting some entities for processing and discarding others. The white paper you mentioned has an example of filtering in combination with the use of an index.
    An alternative is to reverse the procedure above: use the index for 'b' to get a cursor for the "3<=t.b<=5" part of the query, then iterate and filter the results based on the "1<=t.a<=2" expression.
    If you're concerned about efficiency, you can choose the index (i.e., choose which of these two alternatives to implement) based on which part of the query you believe will return the smallest number of results. The less entities read, the faster the query.
    Contrary to what I said earlier, taking the intersection of two queries that are ANDed doesn't make sense -- filtering is the better solution. However, taking the union of two queries does make sense, when the queries are ORed. Sorry for the confusion.
    --mark                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Help with Inner Join query in SQL

    Hope someone can help with this, as this is quite an involved project for me, and I'm just about there with it.
    My table structure is :
    table_packages
    packageID
    package
    packageDetails
    etc
    table_destinations
    destinationID
    destination
    destinationDetails
    etc
    table_packagedestinations
    packageID
    destinationID
    ..so nothing that complicated.
    So the idea is that I can have a package details page which shows the details of the package, along any destinations linked to that package via the packagedestinations table.
    So this is the last part really - to get the page to display the destinations, but I'm missing something along the way....
    This is the PHP from the header, including my INNER JOIN query....
    PHP Code:
    <?php
    $ParampackageID_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    $ParamSessionpackageID_WADApackages = "-1";
    if (isset($_SESSION['WADA_Insert_packages'])) {
      $ParamSessionpackageID_WADApackages = (get_magic_quotes_gpc()) ? $_SESSION['WADA_Insert_packages'] : addslashes($_SESSION['WADA_Insert_packages']);
    $ParampackageID2_WADApackages = "-1";
    if (isset($_GET['packageID'])) {
      $ParampackageID2_WADApackages = (get_magic_quotes_gpc()) ? $_GET['packageID'] : addslashes($_GET['packageID']);
    mysql_select_db($database_connPackages, $connPackages);
    $query_WADApackages = sprintf("SELECT packageID, package, costperpax, duration, baselocation, category, dateadded, agerange, hotel, educational_tours, field_trips, corporate_outings, plant_visits, budget_package, rollingtours, teambuilding, description, offer FROM packages WHERE packageID = %s OR ( -1= %s AND packageID= %s)", GetSQLValueString($ParampackageID_WADApackages, "int"),GetSQLValueString($ParampackageID2_WADApackages, "int"),GetSQLValueString($ParamSessionpackageID_WADApackages, "int"));
    $WADApackages = mysql_query($query_WADApackages, $connPackages) or die(mysql_error());
    $row_WADApackages = mysql_fetch_assoc($WADApackages);
    $totalRows_WADApackages = mysql_num_rows($WADApackages);
    $colname_educationalDestinations = "1";
    if (isset($_GET['PackageID'])) {
      $colname_educationalDestinations = (get_magic_quotes_gpc()) ? packageID : addslashes(packageID);
    mysql_select_db($database_connPackages, $connPackages);
    $query_educationalDestinations = sprintf("SELECT * FROM destinations INNER JOIN (packages INNER JOIN packagedestinations ON packages.packageID = packagedestinations.packageID) ON destinations.destinationID = packagedestinations.destinationID WHERE packages.packageID = %s ORDER BY destination ASC", GetSQLValueString($colname_educationalDestinations, "int"));
    $educationalDestinations = mysql_query($query_educationalDestinations, $connPackages) or die(mysql_error());
    $row_educationalDestinations = mysql_fetch_assoc($educationalDestinations);
    $totalRows_educationalDestinations = mysql_num_rows($educationalDestinations);
    ?>
    And where I'm trying to display the destinations themselves, I have : 
    <table>
            <tr>
                     <td>Destinations :</td>
                </tr>
               <?php do { ?>
            <tr>
                 <td><?php echo $row_educationalDestinations['destination']; ?></td>
            </tr>
            <?php } while ($row_educationalDestinations = mysql_fetch_assoc($educationalDestinations)); ?>
    </table>
    If anyone could have a quick look and help me out that would be much appreciated - not sure if its my SQL at the top, or the PHP in the page, but either way it would be good to get it working. 
    Thanks.

    First off, you need to get the database tables so that there is a relationship between them.
    In fact, if there is a one to one relationship, then it may be better to store all of your information in one table such as
    table_packages
    packageID
    package
    packageDetails
    destination
    destinationDetails
    etc
    If there is a one to many relationship, then the following would be true
    packages
    packageID
    package
    packageDetails
    etc
    destinations
    destinationID
    packageID
    destination
    destinationDetails
    etc
    The above assumes that there are many destinations to one package with the relationship coloured orange.
    Once you have the above correct you can apply your query as follows
    SELECT *
    FROM packages
    INNER JOIN destinations
    ON packages.packageID = destinations.packageID
    WHERE packages.packageID = %s
    ORDER BY destination ASC
    The above query will show all packages with relevant destinations

  • How to build table join query in Jdeveloper

    Hi,
    Can someone tell me how to build table join query in Jdeveloper's Expression Builder UI?

    [Is it possible to create a table of contents in Crystal Reports?|http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_erq/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233313335333133303330%7D.do]

Maybe you are looking for