根据特定属性选择属性

时间:2015-03-06 17:33:38

标签: mysql

我在根据特定属性值从行中选择数据时遇到问题。我们假设我有一个属性id的值和一个包含多个属性的行,包括con_post_id,可以是NULL或另一行id价值(如链接)。如果con_post_id不是NULL,是否可以从当前行和id=con_post_id行中选择其他属性?但如果con_post_idNULL,它会选择行的所有属性,其起始值为id

id  user_id store_id status_id con_post_id con_like_id thought   time                product_flag_id removed views locked type
494      63 NULL             0        NULL        NULL somevalue 2015-03-06 17:14:16             397       0     0      0 user
508      63 NULL             4         494          56           2015-03-06 17:58:50            NULL       0     0      0 user

id=494行的查询应返回其所有属性值,但对id=508行的查询应从当前行返回user_id, status_id,并从thought, product_flag_id, removed, views, locked and type返回id=494 {{1}}的行。

我希望这个问题很清楚。

1 个答案:

答案 0 :(得分:1)

您可以使用左连接自行加入表,然后使用一些条件来确定要显示的值,具体取决于这是否是请求的“子”或“父”记录。

SELECT
  child.user_id AS user_id,
  child.status_id AS status_id,
  IF(
    /*
      if this value is NULL there is no "parent" record
      so get the value from child record
      similar to all values with "IF" condition
    */
    child.con_post_id IS NULL, 
    child.thought,
    parent.thought
  ) AS thought,
  IF(
    child.con_post_id IS NULL, 
    child.product_flag_id,
    parent.product_flag_id
  ) AS product_flag_id,
  IF(
    child.con_post_id IS NULL, 
    child.removed,
    parent.removed
  ) AS removed,
  IF(
    child.con_post_id IS NULL, 
    child.views,
    parent.views
  ) AS views,
  IF(
    child.con_post_id IS NULL, 
    child.locked,
    parent.locked
  ) AS locked,
  IF(
    child.con_post_id IS NULL, 
    child.type,
    parent.type
  ) AS type
FROM table AS child
LEFT JOIN table AS parent
  ON child.con_post_id = parent.id
WHERE child.id = ?