简体   繁体   中英

how to get Rows same value

my sql table like given below

Table name package

pack_id         pack_name
-------         ---------
1               pack1
2               pack2
3               pack3 

Table name items

items_id   pack_id  items_name        pack_name   
--------   -------  ----------        ---------
1             1        cat             pack1    
2             1        dog             pack1
3             1        cow             pack1
4             2        dog             pack2
5             2        cow             pack2
6             3        cat             pack3 

In html I want to show the packages like

Pack1       cat         dog       cow
pack2       dog         cow
pack3       cat

Here first

(items_name)cat = 1(items_id) ,

(items_name)dog = 2(items_id) ,

(items_name)cow = 3(items_id) and then

(items_name)dog = 4(items_id) ,

(items_name)cow = 5(items_id) ans also

(items_name)cat = 6(items_id) like this

here I click the cat means corresponding cat id stored in another table.

You seem to want a variable number of columns which isn't really possible. Could maybe do it if there were a fairly limited number of possible columns.

For flexibility probably best to put the item names in a single column in the results, comma separated:-

SELECT a.pack_name, GROUP_CONCAT(b.items_name )
FROM package a
INNER JOIN items b
ON a.pack_id = b.pack_id
GROUP BY a.pack_id

If you really wanted them in columns and only have a limited number of columns then you could maybe do something like this:-

SELECT a.pack_name, MAX(Col0), MAX(Col1), MAX(Col2), MAX(Col3)
FROM package a
INNER JOIN
(
    SELECT items_id, pack_id, IF(aSequence=0, items_name, NULL) AS Col0, IF(aSequence=1, items_name, NULL) AS Col1, IF(aSequence=2, items_name, NULL) AS Col2, IF(aSequence=3, items_name, NULL) AS Col3
    FROM
    (
        SELECT items_id, pack_id, items_name, @sequence := IF(@prevpack = pack_id, @sequence + 1, 0) AS aSequence, @prevpack := pack_id
        FROM
        (
            SELECT items_id, pack_id, items_name
            FROM items
            ORDER BY pack_id, items_id
        ) Sub1
        CROSS JOIN (SELECT @sequence:=0, @prevpack:=0) Sub2
    ) Sub3
) b
ON a.pack_id = b.pack_id
GROUP BY a.pack_id

But this is hardly readable or efficient. It would also be a pain as you would need to modify it when the max number of columns increases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM