如何根据条件值创建mysql查询结果?

时间:2012-01-16 11:00:36

标签: php mysql sql mysql5

我想要这种出局

ID      Status
100     Viewed
103     Not Viewed
105     Viewed

这是我的sql:

select id, status from status_table where ID in (100, 101,102,103,104,105);

它将显示上述结果,因为在状态表中,其他ID没有任何条目。 ID is foreign key of another table named as table_file table. It contains in another database. So I cannot join the table due to some performance issue.所以我将文件ID作为逗号分隔值传递。但我想要这种结果如何使用任何循环创建它。

ID    Status
100   Viewed
101   Not
102   Not
103   Viewed
104   Not
105   Viewed

有可能吗?请帮帮我。

2 个答案:

答案 0 :(得分:1)

你有一张表存在这些ID吗?那么你可以参加吗?

SELECT
  source.ID,
  status.value
FROM
  source
LEFT JOIN
  status
    ON status.id = source.id
WHERE
  source.ID in (100, 101,102,103,104,105);

如果没有,则需要创建临时表或内联表(其中包含这些值)。然后,您可以将该表加入您的数据。

修改

内联表的示例。有几种方法可以做到这一点,这只是一种。

SELECT
  source.ID,
  status.value
FROM
  (
    SELECT 100 AS id UNION ALL
    SELECT 101 AS id UNION ALL
    SELECT 102 AS id UNION ALL
    SELECT 103 AS id UNION ALL
    SELECT 104 AS id UNION ALL
    SELECT 105 AS id
  )
  AS source
LEFT JOIN
  status
    ON status.id = source.id

答案 1 :(得分:0)

假设缺少ID时“不”,您可以这样做:

SELECT
  so.ID,
  CASE WHEN st.value IS NULL THEN 'Not' ELSE st.value END
FROM
  databasename1..source so
LEFT JOIN
  databasename2..status st
    ON st.id = so.id
WHERE
  so.ID in (100, 101,102,103,104,105)

databasename1databasename2替换为真实database names