简体   繁体   English

如何获得行相同的值

[英]how to get Rows same value

my sql table like given below 我的sql表如下所示

Table name package 表名package

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

Table name items 表名称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 在html中,我想显示类似

Pack1       cat         dog       cow
pack2       dog         cow
pack3       cat

Here first 先来

(items_name)cat = 1(items_id) , (items_name)cat = 1(items_id),

(items_name)dog = 2(items_id) , (items_name)dog = 2(items_id),

(items_name)cow = 3(items_id) and then (items_name)cow = 3(items_id),然后

(items_name)dog = 4(items_id) , (items_name)dog = 4(items_id),

(items_name)cow = 5(items_id) ans also (items_name)cow = 5(items_id)也

(items_name)cat = 6(items_id) like this (items_name)cat = 6(items_id)像这样

here I click the cat means corresponding cat id stored in another table. 在这里,我单击“猫”表示存储在另一个表中的相应猫id。

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. 这也会很麻烦,因为当最大列数增加时,您需要对其进行修改。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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