Inner join with an asymmetric column: plan not optimized SQL

Hello

I think that it is a FAQ, but I was unable to get a useful answer by Googling.

Oracle version is 11.2.0 on Sparc64.

Consider the following code:
drop table x;
PROMPT
PROMPT Populate x with some users. Note the iduser PK
PROMPT

create table x as
select 1 iduser, 'PUBLIC' owner from dual
union
select 2 iduser, 'SYSTEM' owner from dual
union
select 3 iduser, 'XDB' owner from dual
union
select 4 iduser, 'APPQOSSYS' owner from dual
union
select 5 iduser, 'SYS' owner from dual
union
select 6 iduser, 'OUTLN' owner from dual
union
select 7 iduser, 'DBSNMP' owner from dual
/

alter table x add constraint pk_x primary key(iduser);


PROMPT
PROMPT Create a table y from all_objects, but using the previous iduser 
PROMPT as foreign key (owner column is not needed). Note the index
PROMPT on column iduser
PROMPT

drop table y
/
create table y as
select x.iduser, all_objects.*
from all_objects, x
where x.owner = all_objects.owner
and x.owner in  ( 'PUBLIC', 'SYSTEM', 'XDB', 'APPQOSSYS',
    'SYS', 'OUTLN', 'DBSNMP')
/
alter table y drop column owner;
alter table y add constraint y_fk foreign key(iduser) references x;
create index idx_y on y(iduser);

PROMPT
PROMPT Take some stats. X stats are irrelevant, I think
PROMPT
exec dbms_stats.gather_table_stats( -
    USER, -
    'Y', -
    estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, -
    degree => DBMS_STATS.DEFAULT_DEGREE, -
    cascade => true, -
    method_opt => 'FOR COLUMNS IDUSER SIZE AUTO', -
    granularity => 'ALL' -
)
exec dbms_stats.gather_table_stats( -
    USER, -
    'X', -
    estimate_percent => DBMS_STATS.AUTO_SAMPLE_SIZE, -
    degree => DBMS_STATS.DEFAULT_DEGREE, -
    cascade => true, -
    method_opt => 'FOR COLUMNS IDUSER SIZE AUTO', -
    granularity => 'ALL' -
)

set autotrace trace exp

PROMPT
PROMPT APPQOSSYS has only 5 objects (well, your output may vary, but it should by
PROMPT very similar), but the following query ignore the index and do a full scan on Y
PROMPT
select x.*, y.*
from x, y
where x.owner = 'APPQOSSYS'
and y.iduser = x.iduser
/

PROMPT
PROMPT Virtually, equivalent to the previous one. But the explain plan is very different
PROMPT and the index is used
PROMPT

select y.*
from x, y
where x.owner = 'APPQOSSYS'
and y.iduser = 4
/

set autotrace off
The result is:
............................ [snip] .........................

( EXPLAIN PLAN OF FIRST QUERY)

Execution Plan
----------------------------------------------------------
Plan hash value: 1702571549

---------------------------------------------------------------------------
| Id  | Operation          | Name | Rows  | Bytes | Cost (%CPU)| Time     |
---------------------------------------------------------------------------
|   0 | SELECT STATEMENT   |      |   559 | 58136 |   142   (1)| 02:23:19 |
|*  1 |  HASH JOIN         |      |   559 | 58136 |   142   (1)| 02:23:19 |
|*  2 |   TABLE ACCESS FULL| X    |     1 |     9 |     2   (0)| 00:02:02 |
|   3 |   TABLE ACCESS FULL| Y    | 55883 |  5184K|   139   (0)| 02:20:47 |
---------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   1 - access("Y"."IDUSER"="X"."IDUSER")
   2 - filter("X"."OWNER"='APPQOSSYS')



( EXPLAIN PLAN OF SECOND QUERY)

Execution Plan
----------------------------------------------------------
Plan hash value: 2241001346

-------------------------------------------------------------------------------------
| Id  | Operation                   | Name  | Rows  | Bytes | Cost (%CPU)| Time     |
-------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT            |       |    10 |   950 |     2   (0)| 00:02:02 |
|   1 |  TABLE ACCESS BY INDEX ROWID| Y     |    10 |   950 |     2   (0)| 00:02:02 |
|*  2 |   INDEX RANGE SCAN          | IDX_Y |    10 |       |     1   (0)| 00:01:01 |
-------------------------------------------------------------------------------------

Predicate Information (identified by operation id):
---------------------------------------------------

   2 - access("Y"."IDUSER"=4)
Well, the question is very simple: is it possible to get the first query to take the index and to avoid complete analysis? With no clues, of course.

All of your advice and comments will be welcome. Thanks in advance.

Best regards

jjuanino wrote:

Well, the question is very simple: is it possible to get the first query to take the index and to avoid complete analysis? With no clues, of course.

All of your advice and comments will be welcome. Thanks in advance.

This is a limit known optimizer - no realistic solution.

The optimizer can recognize with the help of a histogram iduser on table column is very unevenly distributed, but there is not a generic strategy to recognize what owner on the table of X corresponds to what iduser on the table of Y.

An approach that can help - even if I do not remember seeing documented is to rewrite the query with a subquery and use the / * + precompute_subquery * / tip.
I have not tried with your data, but something like:

select * from y
where iduser in (
    select /*+ precompute_subquery */ x.iduser
    from x
    where owner = 'APPQSYS'
    )
;

Regards
Jonathan Lewis

P.S.  Found a reference note by Tanel Poder: http://blog.tanelpoder.com/2009/01/23/multipart-cursor-subexecution-and-precompute_subquery-hint/

Tags: Database

Similar Questions

  • difference between Inner Join join natural r

    Experts,

    I'm trying to understand the difference between Natural Join and inner join.

    Inner join: the following query provides 106 lines based on two tables

    SQL > SELECT EMPLOYEE_ID EID, last NAME, DEPT_NAME DEPARTMENT_NAME

    2 EMPLOYEES A, B MINISTRIES

    3. WHERE A.DEPARTMENT_ID = B.DEPARTMENT_ID

    4 order employee_id;

    Natural Join: This is the combination or combined result of all the columns in both tables.

    When I run the Sub statement, it combines employees and the table from department of a HR schema and provides only 32 ranks

    SQL > select employe_id, first_name, department_name

    2 departments of NATURAL JOIN employees;


    EMPLOYEE_ID NAME DEPARTMENT_NAME

    ----------- -------------------- -------------------

    Neena 101 Executive

    Lex 102 Executive

    104 Bruce IT

    David 105 HE

    question: why the NATURAL JOIN query omit the employee_id 103 and on what basis it omit a few other employee_id

    Thanks in advance

    Hello

    The main difference is that INNER JOIN is used in real life; NATURAL JOIN is used only in textbooks.

    More rigorously, FRANCKLIN JOIN is an inner join, involving all the columns that have the same name.  The hr.departments and hr.employees have 2 columns with the same name: department_id and manager_id, so

    OF hr.departments d

    NATURAL JOIN e hr.employees

    is equivalent to

    OF hr.departments d

    INNER JOIN hr.employees e ON e.department_id = d.deparment_id

    AND e.manager_id = d.manager_id

    or, using the old join syntax

    OF hr.departments d

    e hr.employees

    WHERE e.department_id = d.deparment_id

    AND e.manager_id = d.manager_id

  • Oracle: Inner join syntax

    Hello
    I am confused with Inner Join syntax.
    According to the defination of Inner Join, it is said that
    Inner joins return all rows in multiple tables satisfied the join condition.

    By the way by examples of inner join in web, join Inner is written in these syntaxes as indicated:

    First syntax:

    SELECT Person.LastName, Person.FirstName, person Sales.OrderNo INNER JOIN sales on Person.P_Id = Sales.P_Id

    Second syntax:

    SELECT suppliers.supplier_id, suppliers.supplier_name, orders.order_date
    FROM the suppliers orders
    WHERE suppliers.supplier_id = orders.supplier_id;

    Please tell me if the keyword Inner Join its use is mandatory or not?

    Thank you for reading.

    user672373773 wrote:
    First of all, thanks Anurag to your prompt response.

    I have a request here, please tell me why oracle has provided two syntax? This is the ANSI and non-ANSI syntax

    I know, it's the Oracle had a format no ANSI to join since its initial versions. In later versions, oracle decided to except ANSI format too since Oracle want to support the ansi format in almost everything.

    So since he was using the ansi non format, it can't support/stop using only for backward compatibility and also it as having the users to use the ansi format, it is both.

    Concerning
    Anurag

  • using outer joins if the two column is null? Use only (+)

    Hi all

    create the table xxc_tr_num (tl_number number, tr_no number tl_no_id);

    insert into xxc_tr_num values (123,100,222);

    insert into xxc_tr_num values (124,100,333);

    create the table xxc_od_tab (tl_number number, tl_id number);

    insert into xxc_od_tab values (123,001);

    insert into xxc_od_tab values (null, null);

    create table xxc_oth_tab (name varchar2 (10), number of tl_id);

    insert into xxc_oth_tab values('abc',,001);

    insert into xxc_oth_tab values (null, null);

    Wait it out put

    tr_no tl_no_id name

    100 222 abc

    100 333

    using outer joins if the two column is null? use only please of outer joins

    And I tried to use outer joins on both tl_id column but not get values and I use have County (tr_no ) > 1

    Rajesh123 wrote:

    Thank you Kiss it is not possible to use having clause?

    You need to understand the functioning of the group. If you will not be asked this question.

    Check this box

    SQL> select tr_no,
      2         tl_no_id,
      3         count(*)
      4    from xxc_tr_num a,
      5         xxc_od_tab b,
      6         xxc_oth_tab c
      7   where a.tl_number = b.tl_number(+)
      8     and b.tl_id = c.tl_id(+)
      9   group
     10      by tr_no
     11       , tl_no_id;
    
         TR_NO   TL_NO_ID   COUNT(*)
    ---------- ---------- ----------
           100        333          1
           100        222          1
    

    See what returns the count? You have grouped according to TR_NO and TL_NO_ID. You must take into consideration the TL_NO_ID just put COUNT (TR_NO) does not increase the NUMBER of the whole group. To get the NUMBER on the whole group, I used the analytical function and did. Like this, see the number of the analytical function here

    SQL> select tr_no,
      2         tl_no_id,
      3         count(*),
      4         count(*) over(partition by tr_no)
      5    from xxc_tr_num a,
      6         xxc_od_tab b,
      7         xxc_oth_tab c
      8   where a.tl_number = b.tl_number(+)
      9     and b.tl_id = c.tl_id(+)
     10   group
     11      by tr_no
     12       , tl_no_id;
    
         TR_NO   TL_NO_ID   COUNT(*) COUNT(*)OVER(PARTITIONBYTR_NO)
    ---------- ---------- ---------- ------------------------------
           100        222          1                              2
           100        333          1                              2
    

    So to answer your question, yes you can't do in the HAVING clause...

  • inner join is not eliminating duplicates!

    Name of the table is customers

    VALUE CITY SIDE NUMS CNAME
    1 2001 Hoffman 100 1001 London
    2 Rome 2002 200 1003 Giovanni
    3 2003 Liu San Jose 200 1002
    4 2004 grass Berlin 300 1002
    5 2006 Clemens 100 1001 London
    6 2008 Cisneros San Jose 300 1007
    7 2007 perish Rome 100 1004

    Query is
    To find all pairs of customers having the same side

    I tried:

    SELECT c.cname, cb.cname FROM customers c INNER JOIN customers cb WE cb.rating AND c.cname = c.rating! = cb.cname

    CNAME CNAME
    1 perish Hoffman
    2 Clemens Hoffman
    3 Liu Giovanni
    4 Giovanni Liu
    5 Cisneros grass
    6 perira Clemens
    7 Hoffman Clemens
    8 grass Cisneros
    Clemens 9 perish
    10 Hoffman perish


    Ideally, it should up to 5 rows, but it does not return these lines for an e.g. Hoffman perish since I'm Perira Hoffman already. Your answers will be appreciated.

    Thank you
    Vaibhav

    Hi, Vaibhav,

    914683 wrote:
    Name of the table is customers

    VALUE CITY SIDE NUMS CNAME
    1 2001 Hoffman 100 1001 London
    2 Rome 2002 200 1003 Giovanni
    3 2003 Liu San Jose 200 1002
    4 2004 grass Berlin 300 1002
    5 2006 Clemens 100 1001 London
    6 2008 Cisneros San Jose 300 1007
    7 2007 perish Rome 100 1004

    Query is
    To find all pairs of customers having the same side

    I tried:

    SELECT c.cname, cb.cname FROM customers c INNER JOIN customers cb WE cb.rating AND c.cname = c.rating! = cb.cname

    Perhaps what you want is

    SELECT      c.cname
    ,         cb.cname
    FROM          customers  c
    INNER JOIN  customers  cb  ON   c.rating  = cb.rating
                                       AND  c.cname       < cb.cname     -- not !=
    ;
    

    CNAME CNAME
    1 perish Hoffman
    2 Clemens Hoffman
    3 Liu Giovanni
    4 Giovanni Liu
    5 Cisneros grass
    6 perira Clemens
    7 Hoffman Clemens
    8 grass Cisneros
    Clemens 9 perish
    10 Hoffman perish

    The title you chose for this thread is "inner join is not eliminating duplicates!
    Inner joins (or other types of joints) are not supposed to remove duplicates. Use SELECT DISTINCT to remove duplicates, which is exactly the same lines.
    You don't have to duplicate. For example, these lines of your result set:

    `        CNAME     CNAME
    1     Perira     Hoffman
    10     Hoffman     Perira
    

    are not identical; Indeed, the two columns are different.

    Ideally, it should up to 5 rows, but it does not return these lines for an e.g. Hoffman perish since I'm Perira Hoffman already.

    Please report the exact output of the sample data you want. (As said by Hoek, post CREATE TABLE and INSERT statements for the sample data too.)

  • Update with INNER JOIN

    Hello

    My update with the inner join does not seem to work.

    UPDATE RECAP R SET R.FLAVOR = (SELECT FN. FLAVOR_NDC FN FLAVOR, REPLACE CAP R WHERE R.NDC11 = FN. NDC11)

    When I write the query above, the inner circle question (SELECT FN. FLAVOR_NDC FN FLAVOR, REPLACE CAP R WHERE R.NDC11 = FN. NDC11) returns multiple lines, and it's a new syntax for me (as I was Teradata and SQL server).

    Can you please how this request can be written to make it work?

    I get the error message below

    SQL error: ORA-01427: einreihig subquery returns multiple rows
    01427 00000 - "einreihig subquery returns several lines.

    1. fix your code:

    UPDATE RECAP R SET R.FLAVOR = (SELECT FN.FLAVOR FROM FLAVOR_NDC FN WHERE R.NDC11 = FN.NDC11)
    

    2. you can use the fusion

    merge into RECAP R
    using FLAVOR_NDC FN
    on(R.NDC11 = FN.NDC11)
    when matched then
         update
         set R.FLAVOR = FN.FLAVOR
    

    Kind regards
    Malakshinov Sayan

  • I want to get only year sysdate with my name of the defined column. but not able to get it.

    I want to get only year sysdate with my name of the defined column. but not able to get it.

    SQL > select to_char (sysdate, 'yyyy') as 'mahesh tyagi' from dual;

    Mahé

    ----

    2015

    SQL > select to_char (sysdate, 'yy') as 'Manu' from dual;

    my

    --

    15

    So I couldn't do 'Manu' or "mahesh tyagi" as the column name.

    The column name is "mahesh tyagi" is simply displayed it shortened to sqlplus due to the known values in the column length.

    create table year_test select to_char (sysdate, 'yyyy') "mahesh tyagi" double;

    year_test / / DESC

    You can change the way sqlplus displays the header of column with something like

    column "mahesh tyagi" format a15

  • Understand the joins with more than one column?

    Hi all

    I want to know if I understand.

    When you join two tables, and the join condition has four columns (two for each table) as follows:

    where d.deptno = e.deptno

    and d.name = e.name

    I think it means the engine must choose "the selection list" when he sees a number of d.deptno (for example 10) equal number in e.deptno, and

    the d.name from the same folder (10) must be equal to the value of e.name.

    I understand?

    Another example, I want to understand, when we say:

    where d.deptno = e.deptno

    and d.deptno = s.deptno

    This means that the number (10) should for example equal to one (10) in the table (e), and the same 10 must be equal to a value in the table (s)?

    Am I wrong?

    Thank you

    Hello

    Yes, what you say is right; but don't take my word for it.  Try it yourself.   Create a couple of small tables.  Insert some data that matches (and will appear in the results of joints) and others that does not (and should not be in the results) and see if the results are what you expected.

  • Line 1 columns do not merge with Row 2 columns in InDesign Script

    It is my code: -.

    var myTableFrame.insertionPoints = myTable [0].tables.add ({columnCount:3, headerRowCount:1, bodyRowCount:2});})

    myTable.rows [0] .cells [0] .silence = "A";

    myTable.rows [0] .cells [0].merge(myTable.rows[1].cells[0]);

    But:-below the job line: -.

    myTable.rows [0] .cells [0].merge(myTable.rows[0].cells[1]);

    myTable.rows [1] .cells [0].merge(myTable.rows[2].cells[0]);


    ------------------------------------------------------------------------------

    Problem is that column 1 & 2 of the fusion of line 1

    and the column 1 row 2 & 3 fusion

    but, to the column 1 rank 1 & 2 fusion has not and no column of row 1 merger with column of line 2

    Can someone help me please...

    Thank you...

    Problem solved: -.

    1. we cannot merge with bodyRow headerRow columns...

    2. we can merge with headerRow headerRow columns...

    3. we can merge with bodyRow bodyRow columns...

    In the case of line 1 should be used below line: -.

    var myTableFrame.insertionPoints = myTable [0].tables.add ({columnCount:3, headerRowCount:2, bodyRowCount:2});})

    OR

    var myTableFrame.insertionPoints = myTable [0].tables.add ({columnCount:3, bodyRowCount:3});})

  • generator 10 I have a query with an inner join... join error unsupported expression! In a query, Report Designer cannot do a join?

    Hey in the 10 Report Builder Query Builder, I got an error:

    OftblFacility INNER JOIN tblStateProvince ON tblFacility.OIDStateProvince = tblStateProvince

    What is java.swl.SQLException: [Macromedia] [SequeLinkJDBC Driver] [ODBC Socket] [Microsoft] [ODBC Microsoft Access driver] Join expression not taken in charge.

    Why?

    Report Designer will automatically join tables only if you have defined a relationship between them in your database.

    In Report Designer, you can easily create a join by dragging a field from one table to the related field in the other table. It couldn't be simpler.

    See you soon

    Eddie

  • Help with Inner join problem

    The following query works fine as long as there is a value in the subID field, which is the end of the inner join statement. If the subID is empty then no data is output, even if it is there. Try as I may, I can't do the right solution in which the statement to get the data to show without the subID. What Miss me?

    < name cfquery = "getInfo" datasource = "#application.database #" >

    Select page_id, pageName, pages.content, pages.cat_id, pages.seo_title, pages.seo_desc, pages.seo_words, pages.h1_title, pages.pic, pages.brochure, pa ges.video, catagories.catagory, subcat.subID, subcat.sub_category

    (page INNER JOIN categories ON pages.cat_id = catagories.cat_id) INNER JOIN subcat ON pages.subID = subcat.subID

    where pages.page_id = #page_id #.

    < / cfquery >

    Rick,

    Looks like you need a LEFT OUTER join to the table "subcat", so that all the records for the 'pages' and 'categories' are returned, even if no records matching "subcat" doesn't exist.  Joins INTERNAL returns only the selected records when both sides of the join statement tables have matching values, while you will get a join OUTER LEFT (sometimes also known simply as a LEFT JOIN) * everything * selected records from the table on the left side of the join statement, no matter if he adapt records from the table on the right side of the join statement.  When there is no corresponding record in the table on the right side of the join statement, all the columns in your SELECT clause that come from the table on the right side of the join statement will contain NULL values.

    HTH,

    -Carl V.

  • problem with a query, inner join

    Hello;

    I am trying innerjoin these 2 tables in my request for a page that will allow you to add / modify records. Right now, it tells me that I have a lag of data. I do not see where I was wrong. Can someone help me?


    This is my code:

    < name cfparam = "url. CategoryID"type ="integer"default ="0">
    < name cfparam = 'subID' type = 'integer' default = '#url. CategoryID #">"
    < name cfparam = "subName" default = "" >
    < name cfparam = "CategoryID" default = "" >
    < name cfparam = "Name" default = "" >

    < cfif url. CategoryID GT 0 >
    < name cfquery = "categRec" dataSource = "#APPLICATION.dataSource #" >
    SELECT merchSubCat.subName, merchSubCat.subID, categories. CategoryID, Categories.Name
    OF merchSubCat
    JOIN INTERNAL categories
    ON merchSubCat.CategoryID = categories. CategoryID
    WHERE merchSubCat.subID = < cfqueryparam value = '#url. "CategoryID #" cfsqltype = "cf_sql_integer" >
    < / cfquery >

    <!-if the records were found, store the values->
    < cfif categRec.RecordCount EQ 1 >
    < cfset CategoryID = categRec.subID >
    < cfset subName = categRec.subName >
    < cfset CategoryID = categRec.CategoryID >
    < cfset Name = categRec.Name >
    < / cfif >
    < / cfif >

    It's my mistake:

    Run database query error.

    [Macromedia] [SequeLink JDBC Driver] [ODBC Socket] [Microsoft] [ODBC Microsoft Access driver] Type in an expression mismatch.
    The error occurred in C:\Websites\187914kg3\admin\cms\merchant\merchSub-edit.cfm: line 16

    14 : INNER JOIN Categories
    15 :     ON merchSubCat.CategoryID = Categories.CategoryID
    16 : WHERE merchSubCat.subID = <cfqueryparam value="#url.CategoryID#" cfsqltype="cf_sql_integer">
    17 : </cfquery>
    18 : 
    

    I don't see what I did wrong, another pair of eyes can see where I missed something?

    Thank you

    I think that you just want to use the URL. CategoryID parameter:


    Ken Ford

  • outer join with the additional constraint

    Hello

    With the help of Oracle 11 g R2.

    I would of outer join tables 2 together and put down restrictions on the types of records that are returned in the query result. Here's a mock-up of the tables and data.

    create table aaa (col1 number not null, col2 number not null)

    create table bbb (col1 number not null, col2 number not null)

    insert into values of aaa (1: 80)

    insert into values aaa (2, 90)

    insert into values aaa (3, 80)

    insert into values aaa (4, 90)

    insert into values aaa (5, 80)


    insert into bbb values (3, 600)

    insert into values of bbb (4, 700)

    This is the query

    
    select a.col1, a.col2, b.col1, b.col2
    from aaa a, bbb b
    where a.col1 = b.col1 (+)
    and   (a.col2, b.col2) <> ((90, 700))
    

    The result of the query is as follows.

    col1 col1 col2 col2

    1 80

    3 80 3 600

    5 80

    Where col1 = 4 has been deleted, which is an expected result. However, where col1 = 2 has also been removed, which is not a desired outcome. Your response is appreciated.

    Hello

    Here is a way that works for the given sample data:

    SELECT *.

    AAA a

    LEFT OUTER JOIN bbb b ON a.col1 = b.col1

    WHERE the NVL (a.col2, 0) <> 90

    OR NVL (b.col2, 0) <> 700

    ;

    I don't know if that will satisfy your requirements with other data, since you didn't say what your needs are.

    Whenever you have a WHERE clause is applied after the outer join, all columns of the table in option (table bbb in this example) must be used in an NVL, NVL2 or something like a CASE expression that takes into account null values; otherwise, the effect will be the same as an inner join.

  • Help of query SQL - inner joins and the separate results

    Hello

    ASP VB, SQL Server

    I have a structure of data base with 3 tables - users, albums and photos. each user has a identifier unique, each record has a unique albumid and also contains a column with the user name. each record in the photo has a unique id so that store the user name and the album in which the image belongs.

    I'm writing a query that returns a list of the albums for a particular user (based on a user name query string) and who will also bring back the id of the first record in the table for each of these albums photo.

    the closest I get is to run a query to select albumid albums where userid = varuserid with a join internal on the pictures table to remove the photo ID - problem I then it comes out all the photos from the photos table where userid = varuserid, so when I do a repeat region to display a list of albums for a certain user It produces a list of all the photos where userid = varuserid

    I really want to return just a list of ID album based on the username variable, but also to return the first record in the table of photos for each of these albumids

    I tried different combinations of inner joins, select distinct etc but no joy.

    any suggestion would be appreciated as am floundering here...




    First, you must define 'first' with regard to the photos. Is there a
    timestamp? They are numbered inside the album? Do you really care who is
    "first", or do you want simply a shot? You also neglected to indicate if they are
    empty photo albums have been allowed. I assumed that the empty albums are not
    allowed.

    Whatever you decide, the answer will be similar.
    SQL Server tends to get better results with joins with subqueries. You will have
    See such a written request more often with subqueries, and there isn't
    nothing wrong with that, but I'll use a join on a derived table. I have
    have not all column names (hint, hint), so I made them, but the
    Comments should help out you.

    SELECT A.Title, P.PhotoID, P.Caption, A.AlbumID, P.ImagePath
    FROM dbo. A albums
    -build a table derived, consisting of photo ID lowest for each
    album.
    INNER JOIN (SELECT AlbumID, MIN (PhotoID) AS FirstPhoto FROM dbo. Photos
    AlbumID GROUP) AS PM WE A.AlbumID = PM. AlbumID
    -details of the photo for the photo shown in the table above
    INNER JOIN dbo. Photos P on A.AlbumID = P.AlbumID AND
    H. FirstPhoto = P.PhotoID
    User A.UserID ='some WHERE '

    "tedstar" wrote in message
    News:ee4pfn$de$1@forums. Macromedia.com...
    > I am writing a query that returns a list of the albums for a
    > particular user (based on a user name query string) and also bring
    > return
    > the id of the first record in the table for each of these albums photo.

  • Write a SQL query with lines in columns

    All the

    I need help in writing a SQL query with lines in columns, let give u an example...

    drop table activity;

    CREATE TABLE 'ACTIVITY '.

    (

    "PROJECT_WID" NUMBER (22.0) NOT NULL,

    VARCHAR2 (150 CHAR) "PROJECT_NO."

    VARCHAR2 (800 CHAR) 'NAME '.

    );

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (1683691, '10007', 12-121');

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (1684994, '10008', 12-122');

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (1686296, '10009', 12-123');

    Insert in the ACTIVITY (PROJECT_WID, PROJECT_NO, NAME) values (2225222, '9040', 12-124');

    drop table lonet;

    CREATE TABLE 'LONET.

    (

    VARCHAR2 (150 CHAR) "NAME."

    NUMBER OF THE "ROOT."

    VARCHAR2 (150 CHAR) "ENTRYVALUE".

    );

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("GAC", 1683691, "LDE");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('NAM', 1683691, 'LME');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('BAG', 1683691, 'ICE');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('PAP', 1683691, 'IKE');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('NAM', 1686291, "QTY");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('PAP', 1686291, 'MAX');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("GAC", 1684994, "MTE");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('PAP', 1684994, 'MAC');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('FMT', 1684994, 'NICE');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('FMR', 1684994, 'RAY');

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ('BAG', 1686296, "CAQ");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("PAP", 1686296, "QAQ");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("VANESSA", 1686296, "THEW");

    INSERT INTO LONET (NAME, ROOT, ENTRYVALUE) VALUES ("ANDR", 1686296, "REYL");

    commit;

    Link: activity.project_wid = lonet.root

    look like output

    Project_wid Project_no NAME GAC NAM BAG RAC
    16836911000712-121LDELMELCELKE
    16849941000812-122MTEnullnullMAC
    16862961000912-123nullnullCAQQAQ
    2225222904012-124nullnullnullnull

    two problems, in that I am running

    1. I dono how simply we can convert rows to columns

    2. for root = 1683691, there are double NAM and RAC in lonet table... ideally these data should not be there, but since its here, we can take a MAX so that it returns a value

    3. There are undesirables who should be ignored

    Once again my thought process is that we join the activity and 4 alias table lonet.

    ask for your help in this

    Thank you

    Hello

    This is called pivoting.

    Here's a way to do it:

    WITH relevant_data AS

    (

    SELECT a.project_wid, a.project_no, b.SID

    , l.name AS lonet_name, l.entryvalue

    Activity one

    LEFT OUTER JOIN lonet l.root = a.project_wid l

    )

    SELECT *.

    OF relevant_data

    PIVOT (MAX (entryvalue)

    FOR lonet_name IN ("GAC" IN the gac

    "NAM" AS nam

    'BAG' IN the bag

    "RAC" AS cars

    )

    )

    ORDER BY project_wid

    ;

    Output:

    PROJECT_WID PROJECT_NO GAC NAM BAG RAC NAME

    ----------- ---------- ---------- ---------- ---------- ---------- ----------

    1683691 12 - 10007 121 LDE LME LCE LKE

    1684994 MAC MTE 10008 12-122

    1686296 12 - 10009 123 QAC QAQ

    2225222 9040 12 - 124

    To learn more about swivel, see the FAQ in the Forum: Re: 4. How can I convert rows to columns?

    Thanks for posting the CREATE TABLE and INSERT statements; It's very useful!

Maybe you are looking for