Viewed   99 times

I have 2 tables as below

Notes Table

??????????????????????????????
? nid      ?    forDepts     ?
??????????????????????????????
? 1        ? 1,2,4           ?
? 2        ? 4,5             ?
??????????????????????????????

Positions Table

??????????????????????????????
? id       ?    name         ?
??????????????????????????????
? 1        ? Executive       ?
? 2        ? Corp Admin      ?
? 3        ? Sales           ?
? 4        ? Art             ?
? 5        ? Marketing       ?
??????????????????????????????

I am looking to query my Notes table and associate the 'forDepts' column with values from the Positions table.

The output should be:

    ?????????????????????????????????????????
    ? 1        ? Executive, Corp Admin, Art ?
    ? 2        ? Art, Marketing             ?
    ?????????????????????????????????????????

I know that the database should be normalized but I cannot change the database structure for this project.

This is going to be used to export a excel file with the code below.

<?PHP

    $dbh1 = mysql_connect($hostname, $username, $password); 
    mysql_select_db('exAdmin', $dbh1);


    function cleanData(&$str)
  {
    $str = preg_replace("/t/", "\t", $str);
    $str = preg_replace("/r?n/", "\n", $str);
    if(strstr($str, '"')) $str = '"' . str_replace('"', '""', $str) . '"';
  }

    $filename = "eXteres_summary_" . date('m/d/y') . ".xls";

    header("Content-Disposition: attachment; filename="$filename"");
    header("Content-Type: application/vnd.ms-excel");
    //header("Content-Type: text/plain");

    $flag = false;


    $result = mysql_query(
    "SELECT p.name, c.company, n.nid, n.createdOn, CONCAT_WS(' ',c2.fname,c2.lname), n.description 
     FROM notes n 
     LEFT JOIN Positions p ON p.id = n.forDepts
     LEFT JOIN companies c ON c.userid = n.clientId
     LEFT JOIN companies c2 ON c2.userid = n.createdBy"
     , $dbh1);



    while(false !== ($row = mysql_fetch_assoc($result))) {
        if(!$flag) {
            $colnames = array(
                'Created For' => "Created For",
                'Company' => "Company",
                'Case ID' => "Case ID",
                'Created On' => "Created On",
                'Created By' => "Created By",
                'Description' => "Description"
            );
            // display field/column names as first row
            echo implode("t", array_keys($colnames)) . "rn";
            $flag = true;
    }


        $row['createdOn'] = date('m-d-Y | g:i a', strtotime($row['createdOn']));

    array_walk($row, 'cleanData');
    echo implode("t", array_values($row)) . "rn";
  }
  exit;

  ?>

This code outputs only the first value of 'forDepts'

Exa: Executive (instead of Executive, Corp Admin, Art)

Can this be accomplished by CONCAT or FIND_IN_SET?

Please help! Thanks in advance!

 Answers

3
SELECT  a.nid,
        GROUP_CONCAT(b.name ORDER BY b.id) DepartmentName
FROM    Notes a
        INNER JOIN Positions b
            ON FIND_IN_SET(b.id, a.forDepts) > 0
GROUP   BY a.nid
  • SQLFiddle Demo
Monday, November 28, 2022
5

This is a sign of bad DB design you should first look into Database Normalization and if you can change the structure then first normalize it by using a junction table ,As of now you can use FIND_IN_SET() to find your corresponding record id in your comma separated ids column

SELECT * FROM table 
WHERE  FIND_IN_SET('id1',column) > 0
AND FIND_IN_SET('id2',column) > 0
AND FIND_IN_SET('id3',column) > 0

Change the operator as per your wish i have shown example with AND operator,note you need to use FIND_IN_SET as many times as the no of ids you have in your array that you need to compare with your column

Thursday, September 8, 2022
 
bjnvnen
 
4

Use FIND_IN_SET() function:

Try this:

SELECT A.allocationId, 
       B.className, 
       GROUP_CONCAT(C.subjectShortName) AS subjectName
FROM subjectAllocation A
INNER JOIN class_Master B ON A.classId = B.classId 
INNER JOIN subject_Master C ON FIND_IN_SET(C.subjectId, A.subjectId) 
GROUP BY A.allocationId;
Tuesday, November 8, 2022
 
rocks6
 
3

You need the group by for the not aggregated columns

SELECT tab_sector.sector_id,tab_sector.sector_title,tab_sector.sector_desc
    ,tab_sector.sector_image,group_concat(tab_sector_subdivisions.subdiv_id )
LEFT JOIN tab_sector_subdivisions 
        ON tab_sector_subdivisions.sector_id = tab_sector.sector_id 
              AND tab_sector.active = 'Y'
GROUP BY  tab_sector.sector_id,tab_sector.sector_title,
     tab_sector.sector_desc, tab_sector.sector_image
Thursday, August 25, 2022
 
4

Join on the table2_city table twice and use an alias:

SELECT table1_ride.id, fc.name as from_city_name, tc.name as to_city_name
FROM table1_ride
INNER JOIN table2_city AS fc ON
    table1_ride.from_which_city=fc.id
INNER JOIN table2_city AS tc ON
    table1_ride.to_which_city=tc.id

(replace inner with left outer if necessary...).

Monday, December 19, 2022
 
slevin
 
Only authorized users can answer the search term. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :