我有一张像这样的表“Photo_users”:
ID姓名姓名Title1 Title2
其中Title1和Title2是用户“Name Surname”上传的两张照片的标题。我想导出一个与各自作者的照片标题列表(每个作者当然最多有2张照片):
Name Surname Title1
Name Surname Title2
...
...
...
我知道数据库的结构不是我想做的最好的结构,但这就是我所拥有的。
任何提示?谢谢! :)
答案 0 :(得分:3)
select name, surname, title1 from photo_users
union all
select name, surname, title2 from photo_users
如果需要,请添加其他NULL
项检查或将UNION ALL
更改为UNION
以避免重复检索
答案 1 :(得分:2)
SELECT name, surname, title1 AS title
FROM photo_users
UNION
SELECT name, surname, title2 AS title
FROM photo_users
如果你想要它排序/过滤....
SELECT *
FROM (
SELECT name, surname, title1 AS title
FROM photo_users
WHERE id>100
UNION
SELECT name, surname, title2 AS title
FROM photo_users
WHERE id>100
) AS ilv
ORDER BY surname, name;
答案 2 :(得分:2)
SELECT
u.Name,
u.Surname,
CASE x.t
WHEN 1 THEN u.Title1
WHEN 2 THEN u.Title2
END AS Title
FROM Photo_users u
CROSS JOIN (SELECT 1 AS t UNION ALL SELECT 2) x
答案 3 :(得分:1)
( SELECT name
, surname
, title1 AS title
FROM photo_users
WHERE title1 IS NOT NULL
)
UNION ALL
( SELECT name
, surname
, title2 AS title
FROM photo_users
WHERE title2 IS NOT NULL
)
但首先,请考虑规范化您的表格。
它真的像
一样简单photo
,其中包含字段title
和userid
(表photo_users
的外键)以及其他相关和非规范化字段(如photo
)你可能有。title
photo_users
然后你就可以
了JOIN
UNION
查询NULL
。