MySQL joins

Ive cut this bit of code directly from access so it should be ok
String
sql ="SELECT documents.path, documents.title, documents.subject, documents.author, words.documentid, words.word, words.score" +
"FROM words INNER JOIN documents ON words.documentid = documents.docid" + "WHERE (((words.word)='"+word+"'));";
But I get an SQL Exception, which says there is an error near
INNER JOIN documents ON words.documentid = documents.docid" + "WHERE (((words.word)='"+word+"'));";
I'm using the MySQL Connector/J can it use joins??

Ive cut this bit of code directly from access so it
should be ok
String
sql ="SELECT documents.path, documents.title,
documents.subject, documents.author, words.documentid,
words.word, words.score" +
"FROM words INNER JOIN documents ON words.documentid =
documents.docid" + "WHERE
(((words.word)='"+word+"'));";
But I get an SQL Exception, which says there is an
error near
INNER JOIN documents ON words.documentid =
documents.docid" + "WHERE
(((words.word)='"+word+"'));";
I'm using the MySQL Connector/J can it use joins??
this should work...
String sql ="SELECT documents.path, documents.title, documents.subject, documents.author, words.documentid, words.word, words.score";
sql = sql+" FROM words JOIN documents WHERE words.documentid = documents.docid AND (((words.word)='"+word+"'))";

Similar Messages

  • Mysql - Joining a non-related table to other related tables ?

    Can someone help me out here? I have 5 tables in my db:
    staff_tbl
    officelocations_tbl
    title_tbl
    city_tbl
    state_tbl
    I am trying to link my title_tbl with the following sql statement but I cannot figure out how because its not related to the office_tbl at all its only referrenced in the staff_tbl... each staff member has a number attached a 1-14 or so which is then related to the titles_tbl.
    I have had some help creating the statement that I have so far which is:
    SELECT officelocations_tbl.*,city_tbl.*, state_tbl.* ,
    contact1.firstName AS c1Firstname, contact1.lastName AS c1lastName, contact1.middleInitial AS c1middleInitial, contact1.suffix AS c1suffix, contact1.accredations AS c1accredations, contact1.phone AS c1Phone,
    contact1.faxNumber AS c1FaxNumber, contact1.mobilePhone AS c1Mobile, contact1.email AS c1Email,
    contact2.firstName AS c2Firstname, contact2.lastName AS c2lastName, contact2.middleInitial AS c2middleInitial, contact2.suffix AS c2suffix, contact2.accredations AS c2accredations, contact2.phone AS c2Phone,
    contact2.faxNumber AS c2FaxNumber, contact2.mobilePhone AS c2Mobile, contact2.email AS c2Email,
    partner.firstName AS c3Firstname, partner.lastName AS c3lastName, partner.middleInitial AS c3middleInitial, partner.suffix AS c3suffix, partner.accredations AS c3accredations, partner.phone AS c3Phone,
    partner.faxNumber AS c3FaxNumber, partner.mobilePhone AS c3Mobile, partner.email AS c3Email
    FROM officelocations_tbl JOIN city_tbl ON (officelocations_tbl.cityID = city_tbl.cityID)
    LEFT OUTER JOIN state_tbl ON (officelocations_tbl.stateID = state_tbl.stateID)
    LEFT OUTER JOIN staff_tbl contact1 ON (contact1.staffID = officelocations_tbl.contact1)
    LEFT OUTER JOIN staff_tbl contact2 ON (contact2.staffID = officelocations_tbl.contact2) 
    LEFT OUTER JOIN staff_tbl partner ON (partner.staffID = officelocations_tbl.partner) "
    I am needing a way to pull the title_tbl info which is a titleID and titleName and echo out the title name into my recoredset which is the above mysql. I hope this makes enough since for some help... Can someone help me out?

    Hi Davide,
    Could you provide an example that helps understanding your scenario (e.g. screenshot of the pivot-table you want to create)?
    Have you read about the concept of disconnected slicers? Even if you do not want to use a slicer to filter down your TAB_TIME table, that concept could help.
    Regards,
    Julian
    Julian Wissel | BI for NAV @ http://en.navbi.com | Blog @ blog.navida.eu

  • MySQL Joining Tables

    I have a MySQL table that contains two user id's, each of a
    different user. I want to make a query that joins that table with
    the user table to fetch the usernames corresponding to both user
    id's. How can this be done?

    "AngryCloud" <[email protected]> wrote in
    message
    news:fgg691$1jt$[email protected]..
    > Sorry, I don't think I explained my question that well.
    Let me rephrase:
    >
    > I have a MySQL table that contains two user id's, each
    of a different
    > user.
    > Each of the id's is in a different column. I want to
    make a query that
    > joins
    > that table with the user table to fetch the usernames
    corresponding to
    > both
    > user id's.
    >
    > Lets say I have a table called Messages. A record in the
    tables shows the
    > Recipient ID is '26' and the Sender ID is '14'. I want
    to create a query
    > that
    > joins that Messages table with the User Data table to
    get the Usernames of
    > each
    > of those users.
    >
    > Just for possible further understand, let me show you an
    example query
    > that
    > does not make sense, but it might help in describing
    what I am trying to
    > achieve.
    >
    > "SELECT messages.recipient_id, messages.sender_id,
    messages.message,
    > user_data.username
    > FROM messages
    > LEFT JOIN user_data ON messages.recipient_id =
    user_data.id
    > LEFT JOIN user_data ON messages.sender_id =
    user_data.id"
    actually this does make sense but you need to apply aliases
    to the tables
    and columns
    SELECT messages.recipient_id, messages.sender_id,
    messages.message,
    recipient_data.username as recipient, sender_data.username
    as sender
    FROM ((messages
    LEFT JOIN user_data AS recipient_data ON
    messages.recipient_id =
    user_data.id)
    LEFT JOIN user_data AS sender_data ON messages.sender_id =
    user_data.id)

  • PHP & MySQL, joining tables

    I have a table in my database with the following fields:
    user_name
    score
    points
    Some users have 30 scores and others have 5.  What I want to do is create a recordset that will calculate the highest 15 points for each user.  Then count the total scores (either 15 or less) and get an average points.  The only way I have been able to figure anything out is by defining an exact user.  I can't get it to calculate it for each users and create a list.
    Any ideas?

    I tried both ways and can't get either to work properly.
    What do you mean at the end where you say #use the user data here?
    I am not to familiar with loops so I am obviously missing something...

  • Translating SQL from MYSQL to ORACLE with more than one outer join.

    I will translate the following sqlquery from MYSQL to ORACLE:
    SELECT ticket.ticket_no,ticket.ticket_dato,ticket.ticket_subject,ticket.customer_id,customer_name,ticket.ticket_own_read, ticket.department_id, department.department_name, priority_name, tickstat_name, tickettype_name
    FROM customer, ticket left join department
    on ticket.department_id = department.department_id left join priority on ticket.priority_id = priority.priority_id
    left join ticketstatus on ticket.tickstat_id = ticketstatus.tickstat_id
    left join tickettype on ticket.tickettype_id = tickettype.tickettype_id
    where ticket.customer_id = customer.customer_id and customer.owner_id =
    #session.owner_id#
    I have tried in ORACLE with:
    SELECT ticket.ticket_no,ticket.ticket_dato,ticket.ticket_subject,ticket.customer_id,customer_name,ticket.ticket_own_read, ticket.department_id, department.department_name, priority_name, tickstat_name, tickettype_name
    FROM customer, ticket ,department, priority, ticketstatus, tickettype
    where
    ticket.department_id(+) = department.department_id and
    ticket.priority_id(+) = priority.priority_id and
    ticket.tickstat_id(+) = ticketstatus.tickstat_id and
    ticket.tickettype_id(+) = tickettype.tickettype_id and
    ticket.customer_id = customer.customer_id and customer.owner_id = #session.owner_id#
    I get an error:
    MERANT][ODBC Oracle driver][Oracle]ORA-01417: a table may be outer joined to at most one other table
    How do I translate the code to ORACLE?

    I think that your syntax is wrong. The (+) operator should be on the right hand table column, not the left hand table column if you want all rows on the left hand table column. If this syntax is really what you want, you can create underlying views for each join condiction.

  • Joining multiple tables across multiple data sources in MYSQL throws error

    Hi all,
    I have to join tables across multiples MYSQL databases
    eg :
    Table T1,T2 from DB1
    Table T3 from DB2
    Columns from T3 are aggregated ( dimensional column ).
    Hence when i query using oracle answers ( say i have columns from T1,T2 and T3 ) , OBIEE tries to a query DB1 by having NULL for columns in T3
    It uses cast(NULL as INTEGER ) for columns from T3 . But MYSQL throws an error because "cast(NULL as INTEGER )" is not supported by MYSQL.
    I tried executing the query generated by OBIEE manually , if i try giving cast(NULL as SIGNED INTEGER ) , it works.
    pasting the query for reference
    select distinct D1.c2 as c1,
    D1.c1 as c2,
    cast(NULL as INTEGER ) as c3
    from
    (select distinct T87.title_id as c1,
    T59.asin as c2
    from
    print_book_catalog T59 left outer join
    title_authority T87 On T59.asin = T87.asin
    where ( T59.asin = '0345378911' )
    ) D1
    I am not able to find any config file to set this property ( and use signed integer instead of integer ) . Even DBFeatures.INI does not have relevant information.
    Can someobody please help me solve this problem.

    Stijn,
    Thank you for the article link. That was very helpful! It seems that I had a few things off as you do need the "This source should be combined with other sources at this level." checked. In my two table source columns for DATA_SOURCE I defined a literal ('086496' and '085597' for the other) in the Column Mapping tab. I pasted the following in the Fragmentation content, checking the "This source..." box on the Content tab:
    eSIS.SANDBOX4_SCHOOLS.DATA_SOURCE = '086496'
    And pasted the following into the WHERE clause, checking "Select distinct values" on the Content tab:
    sandbox4."".OBIEE.NWOCA_SCHOOLS.SCHOOL_CODE = VALUEOF(NQ_SESSION."SCHOOL") AND sandbox4."".OBIEE.NWOCA_SCHOOLS.DATA_SOURCE = VALUEOF(NQ_SESSION."GROUP")
    This took care of my user's security, utilizing the session variables in the WHERE clause. I am now able to generate reports that only one user can access from one data source and share that same report with another user who can only see data from the other data source.
    Many thanks!!!

  • Searching multiple mysql tables, Joins?

    I'm creating a mysql keyword search on my website and I know how to search a single mysql table, my problem is I need to search 15 different tables simultaneously, they also all have the same column names. I was told I have to you JOINS but i've never used them before. How is this done?
    MY SQL SELECT:
    SELECT *
    FROM mytable1
    WHERE keyword LIKE %colname% OR id  LIKE %colname%

    OK, that really doesn't answer my question. Just because they are in different categories is not a valid reason. Why can't they be mixed?
    In any case, you could probably use a UNION query to solve the current problem, but I would have to know more about the complete query. You don't want to use a JOIN.

  • Joining 3 tables in MySQL using PHP

    Hi,
    I have the following 3 sample tables:
    First
    idkey
    fk_second_idkey
    fk_third_idkey
    Second
    idkey
    Third
    idkey
    My SQL is
    SELECT * FROM First INNER JOIN Second ON First.fk_second_idkey = Second.idkey INNER JOIN Third First.fk_third_idkey = Third.idkey AND First.fk_second_idkey = 2;
    It compiles and I get a result set, but its repeated, so if i get back records 2, 3 and 4, the page will show 2, 3 and 4 about 3 times.
    Can anyone assist with the above SQL?
    Thanks.

    Just kind of guessing at what you're trying to do, but if you want it grouped by the first table (one result per first table ID), then something like:
    SELECT * FROM First
    INNER JOIN Second
       ON First.fk_second_idkey = Second.idkey
    INNER JOIN Third
       ON First.fk_third_idkey = Third.idkey
          AND First.fk_second_idkey = 2
    GROUP BY First.idkey;
    ...but I'm unclear on what's happening already and what you need it to do. Are the linked tables a one-to-one relationship? one-to-many?

  • Extracting records from 3 tables using joins in MySQL

    Hi All,
    Pls help me urgently...
    I have a n Order Processing Module and I have 4 tables for this.
    When a new order is placed these 2 tables are populated.
    Order_Customer : records details abt the direct customer/dealer who places the order.
    Order_Product : records the details abt the product (qty, unit price, taxes etc).
    At the Supplier's end the newly placed orders are accepted or rejected and notification is passed on to the despatch dept.
    No when Acceptance authority logs in all the new orders should be viewed..all the previously accepted orders should not be displayed. Here OrderId, OrderDate, Cust/Deal Name (from Order_Customer) and Product, Qty, OrdValue (from Order_Product) are to be displayed. My normal join qry does not work here
    "SELECT * FROM Order_Customer,Order_Product where Order_Customer.OSerialNo NOT IN (SELECT OrdCustSrNo FROM Order_Acceptance) AND Order_Product.OrdCustSrNo NOT IN (SELECT OrdCustSrNo FROM Order_Acceptance) AND Order_Customer.OSerialNo=Order_Product.OrdCustSrNo"
    This gives an error "Unable to load driver.java.sql.SQLException: Syntax error or access violation: You have an error in your SQL syntax near 'SELECT OrdCustSrNo FROM Order_Acceptance) AND Order_Product.OrdCustSrNo NOT IN (' at line 1 "
    Also tried
    "SELECT Order_Customer.* FROM Order_Customer LEFT JOIN Order_Acceptance ON Order_Customer.OSerialNo = Order_Acceptance.OrdCustSrNo where Order_Acceptance.OrdCustSrNo IS NULL";
    Here it gives error Column Name Product not found.
    Similar is the case when moving an Accepted Order to Despatch Dept.
    Need help urgently.

    "SELECT Order_Customer.* FROM Order_Customer LEFT JOIN Order_Acceptance ON Order_Customer.OSerialNo = Order_Acceptance.OrdCustSrNo where Order_Acceptance.OrdCustSrNo IS NULL";
    I think the above query has syntax error. for try with this
    "SELECT * FROM Order_Customer LEFT JOIN Order_Acceptance ON Order_Customer.OSerialNo = Order_Acceptance.OrdCustSrNo and Order_Acceptance.OrdCustSrNo IS NULL";

  • Date syntax for MySql query in SQL Reporting Services

    I am currently trying to link a mysql Stored Procedure to a Microsoft SQL Reporting Server. It is coming up with a Syntax error. I believe this is down to the
    Date_from and Date_to Parameters. The query is below any help would be appreciated 
    DELIMITER $$ 
    USE `mydb`$$ 
    DROP PROCEDURE IF EXISTS `DTI`$$ 
    CREATE DEFINER=`linkeduser`@`%` PROCEDURE `DTI`(IN date_from DATETIME, 
    IN date_to DATETIME) 
    BEGIN 
    SELECT title,gender,firstname,lastname,address1,town,postcode,dob,IF(co.start_date = '00-00-0000', '', CAST(DATE(co.start_date) AS DATE)) AS 'StartDate' 
    FROM cf_user AS us 
    JOIN ca_compliance AS co ON co.user_id = us.user_id 
    WHERE co.start_date BETWEEN date_from AND date_to; 
    END$$ 
    DELIMITER ;

    Hello,
    The dataset query runs on the external data source.
     In your case, you create a report by retrieve data from MySQL database with a stored procedure. The stored procedure will run on MySQL Server and return the result in the Report designer or Report Builder. To solved this issue, please execute the stored
    procedure on the MySQL database and check the syntax error.
    Regards,
    Fanny Liu
    Fanny Liu
    TechNet Community Support

  • Fields missing from MYSQL table in Database Expert

    I have just updgraded from Crystal XI to 2011 and I am still having issues with joining a mysql table to any other table.
    Fields show up in field explorer but when I try to uise Database expert the only filed in the MYSQL table is the ID field.
    Am I missing something here. Same problem with both versions. When I runa report using just the mysql table evrything works fine.

    Typically if the field doesn't show up the CR can't figure out what type it is which means when we query the DB for the field type the client/server returns the wrong type or some type that CR doesn't support.
    How is the field defined on the server?
    Thank you
    Don

  • Weird problem with mysql query and data table buttons !!!!

    Hi,
    I'm using jsc 2 update 1 on windows and mysql 4.1 . I have a page with a data table. One column of the data table contains "Details" buttons.
    Source query for the table is :
    SELECT tbl_tesserati.idtbl_tesserati idTesserato,
    tbl_tesserati.num_tessera,
    tbl_tesserati.nome,
    tbl_societa.codice_meccanografico
    FROM tbl_tesserati
    INNER JOIN tbl_rel_tesserato_discipline_societa ON tbl_tesserati.idtbl_tesserati = tbl_rel_tesserato_discipline_societa.id_tesserato
    INNER JOIN tbl_cariche ON      tbl_rel_tesserato_discipline_societa.id_carica = tbl_cariche.idtbl_cariche
    INNER JOIN tbl_qualifiche ON      tbl_rel_tesserato_discipline_societa.id_qualifica = tbl_qualifiche.idtbl_qualifiche
    INNER JOIN tbl_discipline ON      tbl_rel_tesserato_discipline_societa.id_disciplina = tbl_discipline.idtbl_discipline
    INNER JOIN tbl_societa ON      tbl_rel_tesserato_discipline_societa.id_societa = tbl_societa.idtbl_societa
    LEFT JOIN tbl_province ON tbl_societa.provincia_sede_sociale = tbl_province.idtbl_province
    LEFT JOIN tbl_comuni ON tbl_societa.comune_sede_sociale = tbl_comuni.idtbl_comuni
    LEFT JOIN tbl_rel_tesserato_discipline_praticate ON tbl_rel_tesserato_discipline_praticate.tessera_id=
    tbl_rel_tesserato_discipline_societa.idtbl_rel_tesserato_discipline
    LEFT JOIN tbl_discipline_praticate ON tbl_discipline_praticate.idtbl_disciplina_praticate=tbl_rel_tesserato_discipline_praticate.disciplina_praticata_id
    WHERE
    tbl_tesserati.cognome LIKE ?
    AND tbl_tesserati.nome LIKE ?
    AND tbl_rel_tesserato_discipline_societa.id_societa LIKE ?
    AND tbl_tesserati.idtbl_tesserati LIKE ?
    AND tbl_cariche.idtbl_cariche LIKE ?
    AND tbl_qualifiche.idtbl_qualifiche LIKE ?
    AND tbl_tesserati.data_nascita >= ?
    AND tbl_tesserati.data_nascita<= ?
    AND tbl_discipline.idtbl_discipline LIKE ?
    AND codice_affiliazione LIKE ?
    AND tbl_societa.denominazione LIKE ?
    AND YEAR(tbl_rel_tesserato_discipline_societa.data_scadenza) LIKE ?
    AND (tbl_province.nome LIKE ? OR tbl_province.nome IS NULL)
    AND ( tbl_comuni.nome LIKE ? OR tbl_comuni.nome IS NULL)
    The tbl_tesserati.data_nascita is a mysql date field.
    The click event handler code for the "Details" Button is:
    public String btnModificaTesserato_action() {
            try{
                TableRowDataProvider rowData= (TableRowDataProvider)getBean("currentRowTesserati");
                getRequestBean1().setId_tesserato((Long)rowData.getValue("idTesserato"));          
            } catch(Exception ex) {
                log("errore nella query",ex);
            return "dettaglioTesseratoSocieta";
        }When i run the project and open the page the table is correctly rendered and populated with some rows. But when i click on details button nothing happens, the page is simply reloaded.
    If i set a breakpoint in the code line   TableRowDataProvider rowData= (TableRowDataProvider)getBean("currentRowTesserati");the debbuger does not stop the code execution ! As if the button was never clicked!
    I tried to modify the source query to :
    SELECT tbl_tesserati.idtbl_tesserati idTesserato,
    tbl_tesserati.num_tessera,
    tbl_tesserati.nome,
    tbl_societa.codice_meccanografico
    FROM tbl_tesserati
    INNER JOIN tbl_rel_tesserato_discipline_societa ON tbl_tesserati.idtbl_tesserati = tbl_rel_tesserato_discipline_societa.id_tesserato
    INNER JOIN tbl_cariche ON      tbl_rel_tesserato_discipline_societa.id_carica = tbl_cariche.idtbl_cariche
    INNER JOIN tbl_qualifiche ON      tbl_rel_tesserato_discipline_societa.id_qualifica = tbl_qualifiche.idtbl_qualifiche
    INNER JOIN tbl_discipline ON      tbl_rel_tesserato_discipline_societa.id_disciplina = tbl_discipline.idtbl_discipline
    INNER JOIN tbl_societa ON      tbl_rel_tesserato_discipline_societa.id_societa = tbl_societa.idtbl_societa
    LEFT JOIN tbl_province ON tbl_societa.provincia_sede_sociale = tbl_province.idtbl_province
    LEFT JOIN tbl_comuni ON tbl_societa.comune_sede_sociale = tbl_comuni.idtbl_comuni
    LEFT JOIN tbl_rel_tesserato_discipline_praticate ON tbl_rel_tesserato_discipline_praticate.tessera_id=
    tbl_rel_tesserato_discipline_societa.idtbl_rel_tesserato_discipline
    LEFT JOIN tbl_discipline_praticate ON tbl_discipline_praticate.idtbl_disciplina_praticate=tbl_rel_tesserato_discipline_praticate.disciplina_praticata_id
    WHERE
    tbl_tesserati.cognome LIKE ?
    AND tbl_tesserati.nome LIKE ?
    AND tbl_rel_tesserato_discipline_societa.id_societa LIKE ?
    AND tbl_tesserati.idtbl_tesserati LIKE ?
    AND tbl_cariche.idtbl_cariche LIKE ?
    AND tbl_qualifiche.idtbl_qualifiche LIKE ?
    AND tbl_tesserati.data_nascita >= ?
    OR tbl_tesserati.data_nascita<= ?
    AND tbl_discipline.idtbl_discipline LIKE ?
    AND codice_affiliazione LIKE ?
    AND tbl_societa.denominazione LIKE ?
    AND YEAR(tbl_rel_tesserato_discipline_societa.data_scadenza) LIKE ?
    AND (tbl_province.nome LIKE ? OR tbl_province.nome IS NULL)
    AND ( tbl_comuni.nome LIKE ? OR tbl_comuni.nome IS NULL)
    Using this query everything works well !! The click handler works and the debugger too !!
    I changed only the AND in OR !!!
    I also tried to change mysql-x-x-connector driver but without solving my problem.
    Can someone help me ?
    Thanks
    Giorgio

    You'll find that it is more to do with the way MySql deals with dates than anything else! Depending on how your date field is setup, then try using a BETWEEN statement for those 2 lines in your first query e.g.
    AND ( tbl_tesserati.data_nascita BETWEEN ? AND ?)
    The date column needs to be in the ISO format to work. If you examine your second query output, you might discover that the output is only going to refer to one parameter (probably the OR one). Did you manage to view the output logs from the application server? You would have got an idea from there with a message like stating a conversion error'.
    Alternatively, you could try using the to_days() function and convert it directly to a number which would be a lot easier to deal with. For example:
    AND to_days(tbl_tesserati.data_nascita >= ? )
    AND to_days( tbl_tesserati.data_nascita<= ? )
    Or try the BETWEEN version with to_days() and see what you get.
    More info about date formatting (v5) here:
    http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_to-days
    Before I forget, sometimes you may need to treat dates as Strings rather 'Long' as you did.
    As a matter of interest, did you try your query in a different piece of software?
    If my queries are a little more complicated, I tend to try MySql queries out in the free MySql query browser and also double check in another to verify certain issues. I found it easier to develop SQL in a seperate program then import the final version to JSC making the required modifications for parameters.
    Message was edited by:
    aerostra

  • How Can I use Mysql's  PROCEDURE by Java Can you give me sample???

    �������^���������������H�iBEGIN�`END�u���b�N�j�@��TOP
    ORACLE�@MSSQL�@SSA�@MySQL�@
    ���{�I���������������������������B
    MySQL�������A ORACLE��MSSSQL��������������BEGIN�`END�u���b�N�����s�������������������������B
    ���������s�������������K���X�g�A�h�v���O�����������R���p�C�������K�v�����������B
    �i�����F�������������������A���w�E�������������K�r�����������j
    --drop PROCEDURE sp_hoge;
    --�f���~�^�����X��������
    delimiter //
    CREATE PROCEDURE sp_hoge()
    DETERMINISTIC
    BEGIN
    /* �������� */
    DECLARE mystr VARCHAR(20);
    DECLARE mycnt INTEGER(2);
    /* �l������ */
    SET mycnt = 0;
    SET mystr = '����';
    /* IF�� */
    IF mycnt = 0 THEN
    SET mystr = '�����Q';
    select mystr;
    ELSE
    select '�����R';
    END IF;
    /* CASE�� */
    CASE extract(month from now())
    WHEN 1 THEN SET mystr = '1��';
    WHEN 2 THEN SET mystr = '2��';
    WHEN 3 THEN SET mystr = '3��';
    WHEN 4 THEN SET mystr = '4��';
    ELSE SET mystr = '1�`4�����O';
    END CASE;
    select mystr;
    /* WHILE-LOOP */
    WHILE mycnt <= 5 DO
    SET mycnt = mycnt + 1;
    select mycnt;
    END WHILE;
    /* BEGIN-END�u���b�N������SELECT�������s */
    /* PROCEDURE�������\�iFUNCTION���������������j */
    select * from help_topic;
    END//
    delimiter ;
    --�X�g�A�h�v���V�[�W�����s
    call sp_hoge();
    �X�g�A�h�v���V�[�W�����T���v���i�J�[�\�����g�p������LOOP�����j�@��TOP
    ORACLE�@MSSQL�@SSA�@MySQL�@
    �J�[�\�����g�p����LOOP�������T���v�������B
    �����p�����[�^���w�����������������Y�������������������A���E���w�X�^�b�t�x�������������A�����������w�c���X�^�b�t�F�x���\���������B
    --drop PROCEDURE sp_hoge;
    --�f���~�^�����X��������
    delimiter //
    CREATE PROCEDURE sp_hoge(inum INTEGER(3))
    DETERMINISTIC
    BEGIN
    /* �������� */
    /* �J�[�\���g�p�����f�[�^�L�����f���g�p */
    DECLARE done INT DEFAULT 0;
    /* �������O������ */
    DECLARE v_mystr VARCHAR(20);
    /* �J�[�\���g�p�� */
    DECLARE v_empnm VARCHAR(40);
    DECLARE v_job VARCHAR(20);
    /* �J�[�\������ �� �����������������`���� */
    DECLARE cur1 CURSOR FOR
    select empnm,job from kemp where deptno = inum;
    /* �f�[�^��������LOOP�E�o�p���������� */
    DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done = 1;
    /* �J�[�\���I�[�v�� */
    OPEN cur1;
    /* LOOP */
    LOOPPROC:REPEAT
    FETCH cur1 INTO v_empnm,v_job;
    IF NOT done THEN
    IF v_job = '�X�^�b�t' THEN
    SET v_mystr = '�c���X�^�b�t�F';
    ELSE
    SET v_mystr = '';
    END IF;
    select CONCAT(v_mystr,v_empnm);
    /* ������������LOOP���E�o����������LEAVE�� */
    /* LEAVE LOOPPROC; */
    END IF;
    UNTIL done END REPEAT;
    /* �J�[�\���N���[�Y */
    CLOSE cur1;
    END//
    --�f���~�^���Z�~�R�����i�f�t�H���g�j������������
    delimiter ;
    --�X�g�A�h�v���V�[�W�����s
    call sp_hoge(1);
    12.2. Control Flow Functions
    CASE value WHEN [compare_value] THEN result [WHEN [compare_value] THEN result ...] [ELSE result] END
    CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...] [ELSE result] END
    The first version returns the result where value=compare_value. The second version returns the result for the first condition that is true. If there was no matching result value, the result after ELSE is returned, or NULL if there is no ELSE part.
    mysql> SELECT CASE 1 WHEN 1 THEN 'one'
    -> WHEN 2 THEN 'two' ELSE 'more' END;
    -> 'one'
    mysql> SELECT CASE WHEN 1>0 THEN 'true' ELSE 'false' END;
    -> 'true'
    mysql> SELECT CASE BINARY 'B'
    -> WHEN 'a' THEN 1 WHEN 'b' THEN 2 END;
    -> NULL
    The default return type of a CASE expression is the compatible aggregated type of all return values, but also depends on the context in which it is used. If used in a string context, the result is returned as a string. If used in a numeric context, then the result is returned as a decimal, real, or integer value.
    Note: The syntax of the CASE expression shown here differs slightly from that of the SQL CASE statement described in Section 17.2.10.2, �gCASE Statement�h, for use inside stored routines. The CASE statement cannot have an ELSE NULL clause, and it is terminated with END CASE instead of END.
    IF(expr1,expr2,expr3)
    If expr1 is TRUE (expr1 <> 0 and expr1 <> NULL) then IF() returns expr2; otherwise it returns expr3. IF() returns a numeric or string value, depending on the context in which it is used.
    mysql> SELECT IF(1>2,2,3);
    -> 3
    mysql> SELECT IF(1<2,'yes','no');
    -> 'yes'
    mysql> SELECT IF(STRCMP('test','test1'),'no','yes');
    -> 'no'
    If only one of expr2 or expr3 is explicitly NULL, the result type of the IF() function is the type of the non-NULL expression.
    expr1 is evaluated as an integer value, which means that if you are testing floating-point or string values, you should do so using a comparison operation.
    mysql> SELECT IF(0.1,1,0);
    -> 0
    mysql> SELECT IF(0.1<>0,1,0);
    -> 1
    In the first case shown, IF(0.1) returns 0 because 0.1 is converted to an integer value, resulting in a test of IF(0). This may not be what you expect. In the second case, the comparison tests the original floating-point value to see whether it is non-zero. The result of the comparison is used as an integer.
    The default return type of IF() (which may matter when it is stored into a temporary table) is calculated as follows:
    Expression Return Value
    expr2 or expr3 returns a string string
    expr2 or expr3 returns a floating-point value floating-point
    expr2 or expr3 returns an integer integer
    If expr2 and expr3 are both strings, the result is case sensitive if either string is case sensitive.
    Note: There is also an IF statement, which differs from the IF() function described here. See Section 17.2.10.1, �gIF Statement�h.
    IFNULL(expr1,expr2)
    If expr1 is not NULL, IFNULL() returns expr1; otherwise it returns expr2. IFNULL() returns a numeric or string value, depending on the context in which it is used.
    mysql> SELECT IFNULL(1,0);
    -> 1
    mysql> SELECT IFNULL(NULL,10);
    -> 10
    mysql> SELECT IFNULL(1/0,10);
    -> 10
    mysql> SELECT IFNULL(1/0,'yes');
    -> 'yes'
    The default result value of IFNULL(expr1,expr2) is the more �ggeneral�h of the two expressions, in the order STRING, REAL, or INTEGER. Consider the case of a table based on expressions or where MySQL must internally store a value returned by IFNULL() in a temporary table:
    mysql> CREATE TABLE tmp SELECT IFNULL(1,'test') AS test;
    mysql> DESCRIBE tmp;
    -------------------------------------------+
    | Field | Type | Null | Key | Default | Extra |
    -------------------------------------------+
    | test | char(4) | | | | |
    -------------------------------------------+
    In this example, the type of the test column is CHAR(4).
    NULLIF(expr1,expr2)
    Returns NULL if expr1 = expr2 is true, otherwise returns expr1. This is the same as CASE WHEN expr1 = expr2 THEN NULL ELSE expr1 END.
    mysql> SELECT NULLIF(1,1);
    -> NULL
    mysql> SELECT NULLIF(1,2);
    -> 1
    Note that MySQL evaluates expr1 twice if the arguments are not equal.
    Previous / Next / Up / Table of Contents
    User Comments
    Posted by I W on July 12 2005 5:52pm [Delete] [Edit]
    Don't use IFNULL for comparisons (especially not for Joins)
    (example:
    select aa from a left join b ON IFNULL(a.col,1)=IFNULL(b.col,1)
    It's terrible slow (ran for days on two tables with approx 250k rows).
    Use <=> (NULL-safe comparison) instead. It did the same job in less than 15 minutes!!
    Posted by [name withheld] on November 10 2005 12:12am [Delete] [Edit]
    IFNULL is like oracle's NVL function (these should help people searching for NVL() ..)
    Posted by Philip Mak on May 26 2006 7:14am [Delete] [Edit]
    When using CASE, remember that NULL != NULL, so if you write "WHEN NULL", it will never match. (I guess you have to use IFNULL() instead...)
    Posted by Marc Grue on June 24 2006 2:03pm [Delete] [Edit]
    You can ORDER BY a dynamic column_name parameter using a CASE expression in the ORDER BY clause of the SELECT statement:
    CREATE PROCEDURE `orderby`(IN _orderby VARCHAR(50))
    BEGIN
    SELECT id, first_name, last_name, birthday
    FROM table
    ORDER BY
    -- numeric columns
    CASE _orderby WHEN 'id' THEN id END ASC,
    CASE orderby WHEN 'desc id' THEN id END DESC,
    -- string columns
    CASE orderby WHEN 'firstname' THEN first_name WHEN 'last_name' THEN last_name END ASC,
    CASE orderby WHEN 'descfirst_name' THEN first_name WHEN 'desc_last_name' THEN last_name END DESC,
    -- datetime columns
    CASE _orderby WHEN 'birthday' THEN birthday END ASC,
    CASE orderby WHEN 'desc birthday' THEN birthday END DESC;
    END
    Since the CASE expression returns the "compatible aggregated type of all return values", you need to isolate each column type in a separate CASE expression to get the desired result.
    If you mixed the columns like
    CASE _orderby
    WHEN 'id' THEN id
    WHEN 'first_name' THEN first_name
    ...etc...
    END ASC
    .. both the id and first_name would be returned as a string value, and ids would be sorted as a string to '1,12,2,24,5' and not as integers to '1,2,5,12,24'.
    Note that you don't need a "ELSE null" in the CASE expressions, since the CASE expression automatically returns null if there's no match. In that case, you get a "null ASC" in your ORDER BY clause which doesn't affect the sort order. If for instance orderby is 'descfirst_name', the ORDER BY clause evaluates to:
    ORDER BY null ASC, null DESC, null ASC, first_name DESC, null ASC, null DESC
    Effectively the same as "ORDER BY first_name DESC". You could even add a new set of CASE expressions for a second order column (or more..) if you like.
    Add your own comment.

    What is that post supposed to be?

  • Multiple joins on the same table

    I'm new to SQL 2005 & C# - I'm a MySQL/PHP crossover.
    I'm using s Stored Procedure and I'm trying to do multiple joins onto
    one table.  I have 6 fields in one table that are foreign keys of
    another table:
    Table1
    id
    PrimaryCode
    SecondaryCode1
    SecondaryCode2
    SecondaryCode3
    SecondaryCode4
    SecondaryCode5
    Table 2
    id
    Title
    CommCode
    The fields in table 1 (except is obviously) hold the id of a row in
    Table 2.  When displaying data I want to display "Title" -
    "CommCode" for each item in Table 1.  I got myself started by
    searchig on the net and I have a stored procedure.  The obvious
    problem is that as it goes through the Query only the last value
    remains in place - since each value before it is cleared in the
    UNION.   How can I do this??  Here's my Stored Procedure:
    =====================================
    ALTER PROCEDURE GetRegistersSpecific
    @SearchTxt int
    AS
    SELECT
    registrations.Company,registrations.Address1,registrations.Address2,registrations.City,registrations.State,registrations.Zip,registrations.ContactName,registrations.Phone,registrations.Fax,registrations.Email,registrations.Website,registrations.Feid,registrations.BusinessType,registrations.BackupWitholding,registrations.SignedName,registrations.SignedDate,
    PrimaryCode AS MyID, Title, CommodityCode
    FROM registrations
    JOIN CommodityCodes ON PrimaryCode = CommodityCodes.id
    UNION
    SELECT
    registrations.Company,registrations.Address1,registrations.Address2,registrations.City,registrations.State,registrations.Zip,registrations.ContactName,registrations.Phone,registrations.Fax,registrations.Email,registrations.Website,registrations.Feid,registrations.BusinessType,registrations.BackupWitholding,registrations.SignedName,registrations.SignedDate,
    SecondaryCode1 AS MyID, Title, CommodityCode
    FROM registrations
    JOIN CommodityCodes ON SecondaryCode1 = CommodityCodes.id
    UNION
    SELECT
    registrations.Company,registrations.Address1,registrations.Address2,registrations.City,registrations.State,registrations.Zip,registrations.ContactName,registrations.Phone,registrations.Fax,registrations.Email,registrations.Website,registrations.Feid,registrations.BusinessType,registrations.BackupWitholding,registrations.SignedName,registrations.SignedDate,
    SecondaryCode2 AS MyID, Title, CommodityCode
    FROM registrations
    JOIN CommodityCodes ON SecondaryCode2 = CommodityCodes.id
    UNION
    SELECT
    registrations.Company,registrations.Address1,registrations.Address2,registrations.City,registrations.State,registrations.Zip,registrations.ContactName,registrations.Phone,registrations.Fax,registrations.Email,registrations.Website,registrations.Feid,registrations.BusinessType,registrations.BackupWitholding,registrations.SignedName,registrations.SignedDate,
    SecondaryCode3 AS MyID, Title, CommodityCode
    FROM registrations
    JOIN CommodityCodes ON SecondaryCode3 = CommodityCodes.id
    UNION
    SELECT
    registrations.Company,registrations.Address1,registrations.Address2,registrations.City,registrations.State,registrations.Zip,registrations.ContactName,registrations.Phone,registrations.Fax,registrations.Email,registrations.Website,registrations.Feid,registrations.BusinessType,registrations.BackupWitholding,registrations.SignedName,registrations.SignedDate,
    SecondaryCode4 AS MyID, Title, CommodityCode
    FROM registrations
    JOIN CommodityCodes ON SecondaryCode4 = CommodityCodes.id
    UNION
    SELECT
    registrations.Company,registrations.Address1,registrations.Address2,registrations.City,registrations.State,registrations.Zip,registrations.ContactName,registrations.Phone,registrations.Fax,registrations.Email,registrations.Website,registrations.Feid,registrations.BusinessType,registrations.BackupWitholding,registrations.SignedName,registrations.SignedDate,
    SecondaryCode5 AS MyID, Title, CommodityCode
    FROM registrations
    JOIN CommodityCodes ON SecondaryCode5 = CommodityCodes.id
    WHERE registrations.ID = @SearchTxt
    =====================================
    Thanks

    Well, I tried using UNION ALL and got the same response.  I also tried doing :
    Title AS SecTitle1
    Title AS SecTitle2
    Title AS SecTitle3
    etc...
    I get different values in the Output Window when I execute the query,
    but as expected it only returns the first value since the script
    executes all the way through before it outputs values.
    Here's how I'm executing:
    while (rdr.Read())
                    // get the results of each column
    string company = (string)rdr["Company"].ToString();
    string address1 = (string)rdr["Address1"].ToString();
    string address2 = (string)rdr["Address2"].ToString();
    string city = (string)rdr["City"].ToString();
    string state = (string)rdr["State"].ToString();
    string zip = (string)rdr["Zip"].ToString();
    string phone = (string)rdr["Phone"].ToString();
    string fax = (string)rdr["Fax"].ToString();
    string email = (string)rdr["Email"].ToString();
    string website = (string)rdr["Website"].ToString();
    string feid = (string)rdr["Feid"].ToString();
    string businessType = (string)rdr["BusinessType"].ToString();
    string contactName = (string)rdr["ContactName"].ToString();
    string primaryCode = (string)rdr["PrimTitle"].ToString();
    string secondaryCode1 = (string)rdr["SecTitle1"].ToString();
    string secondaryCode2 = (string)rdr["SecTitle2"].ToString();
    string secondaryCode3 = (string)rdr["SecTitle3"].ToString();
    string secondaryCode4 = (string)rdr["SecTitle4"].ToString();
    string secondaryCode5 = (string)rdr["SecTitle5"].ToString();
    string backUp = (string)rdr["BackupWitholding"].ToString();
    string signedName = (string)rdr["SignedName"].ToString();
    string signedDate = (string)rdr["SignedDate"].ToString();

  • How to use a MAP whithout join table

    Hello
    I am still evaluating KODO ;-)
    I am using kodo 3.1.2 with an evaluation version
    linux (kernel 2.6)
    SUN JDK 1.4.2_04
    MYSQL MAX 4.0.18 -Max
    IDEA 4.0.3 and ANT 1.5.4 (to be exhaustive)
    I am wondering how to configure the following mapping involving a Map. :
    public class Translation {
    private String locale;
    private String txt;
    public class TranslatableDescription {
    /**Map of Key=locale as String; Value = {@link Translation}*/
    ==> private Map translations = new HashMap(); <==
    public void addATranslation(Translation t){
    translations.put(t.getLocale(), t);
    file package.jdo :
    <?xml version="1.0"?>
    <jdo>
    <package name="data">
    <class name="Translation"/>
    <class name="TranslatableDescription">
    <field name="translations">
    <map key-type="java.lang.String"
    value-type="tutorial.data.Translation"/>
    <extension vendor-name="kodo" key="jdbc-key-size" value="10"/>
    </field>
    </class>
    </package>
    </jdo>
    The default Mapping generate a join table : TRANS_TRANSLATION which works
    fine, but I would like to remove this table by adding a
    colonne in the "TRANSLATION" table containing the JDOID of the
    TRANSLATIONDESCRIPTION owner of this TRANSLATION.
    I have made some try like this one in the mapping file
    <class name="TranslatableDescription">
    <field name="translations">
    <jdbc-field-map type="n-many-map" key-column="LOCALE"
    ref-column.JDOID="OWNERJDOID" table="TRANSLATION0"
    value-column.JDOID="JDOID"/>
    </field>
    The schema generated in my DB is correct but when I try to persist some
    objects I have the following Exception :
    727 INFO [main] kodo.jdbc.JDBC - Using dictionary class
    "kodo.jdbc.sql.MySQLDictionary" (MySQL 4.0.18'-Max' ,MySQL-AB JDBC Driver
    mysql-connector-java-3.0.10-stable ( $Date: 2004/01/13 21:56:18 $,
    $Revision: 1.27.2.33 $ )).
    Exception in thread "main" kodo.util.FatalDataStoreException: Invalid
    argument value, message from server: "Duplicate entry '2' for key 1"
    {prepstmnt 8549963 INSERT INTO TRANSLATION0 (JDOID, LOCALESTR, OWNERJDOID)
    VALUES (?, ?, ?) [reused=0]} [code=1062, state=S1009]
    NestedThrowables:
    com.solarmetric.jdbc.ReportingSQLException: Invalid argument value,
    message from server: "Duplicate entry '2' for key 1" {prepstmnt 8549963
    INSERT INTO TRANSLATION0 (JDOID, LOCALESTR, OWNERJDOID) VALUES (?, ?, ?)
    [reused=0]} [code=1062, state=S1009]
    java.sql.BatchUpdateException: Invalid argument value, message from
    server: "Duplicate entry '2' for key 1"
         at kodo.jdbc.sql.SQLExceptions.getFatalDataStore(SQLExceptions.java:42)
         at kodo.jdbc.sql.SQLExceptions.getFatalDataStore(SQLExceptions.java:24)
         at kodo.jdbc.runtime.JDBCStoreManager.flush(JDBCStoreManager.java:594)
         at
    kodo.runtime.DelegatingStoreManager.flush(DelegatingStoreManager.java:152)
         at
    kodo.runtime.PersistenceManagerImpl.flushInternal(PersistenceManagerImpl.java:964)
         at
    kodo.runtime.PersistenceManagerImpl.beforeCompletion(PersistenceManagerImpl.java:813)
         at kodo.runtime.LocalManagedRuntime.commit(LocalManagedRuntime.java:69)
         at
    kodo.runtime.PersistenceManagerImpl.commit(PersistenceManagerImpl.java:542)
         at
    tutorial.CreateTranslatableDescription.main(CreateTranslatableDescription.java:48)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at
    sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
         at
    sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
         at java.lang.reflect.Method.invoke(Method.java:324)
         at com.intellij.rt.execution.application.AppMain.main(Unknown Source)
    I have the feeling that KODO does try to make diffent row in the table
    "TRANSLATION0" for the TRANSLATION and the MAP.
    So, is this kind of mapping supported by KODO and if yes, how can I
    configure it.
    Thank you for your help
    Nicolas

    So, is this kind of mapping supported by KODO and if yes, how can I
    configure it.It is not directly supported. You can fake it using a one-many mapping
    (see thread: Externalizing Map to Collection of PC), but unless you must
    map to an existing schema, it's probably not worth the effort. (Note:
    also there is a bug that actually prevents this from working with 3.1.2;
    the bug is fixed for 3.1.3, but it hasn't been released yet).

Maybe you are looking for

  • How do I get my music of my ipod on to a new computer if the original computer is dead

    My Itunes account with all my music from cd's was on a computer that died. How do I get my new computer to import all the songs and be the primary computer? I deauthorized all, but everytime I connect one of my ipods or ipads it tells me its synced t

  • Cross-references in a different document

    We have used FrameMaker for years (currently Version 7.1). We are in the process of switching to InDesign (CS5). One current project is a print catalog where I put each section in a different document. One of the sections is a list of book titles. An

  • Error Program SAPLRSDRC does not exist

    Dear Experts, While executing a query am getting an error like as follows : - - Error Program SAPLRSDRC does not exist - Eror An exception with the type  CX_SY_PROGRAM_NOT_FOUND occured. Can anyone please guide if any one have facse this kind of issu

  • Gaim again

    hi, I'm posting about this issue for the second time because I'm puzzled. I did a clean install of arch, made a system update, installed gaim at it wont work. this happened to me twice before on 2 others previous installs of arch. then, doing a syste

  • Delete file but not remove from disk kills Yosemite preview all RAW files dimension now 0 X 0?

    Sorry to trouble you but this has never happened before so I need help. I loaded 300 photos into LR 5.7 I deleted 200 of them. But I asked LR not to remove them from the HD in case I might need them again in the future. When I go into Finder, all the