2

我正在尝试存储 EAV 表,但无法正常工作。我得到了结果,但我无法对其进行排序。

这是我的查询:

SELECT
    formFields.uid,
    formFields.formId,
    formFields.postId,
    formFields.name,
    formFields.value
FROM formFields
INNER JOIN formFields aux
    ON (aux.name = "date")
WHERE
    formFields.formId = "1789"
    AND formFields.deleted = 0
    AND formFields.hidden = 0
ORDER BY aux.value DESC

这是表格:

uid formId  postId  name    value
1   1789    1   title   example title #1
2   1789    1   date    1341091600
3   1789    2   title   example title #2
4   1789    2   date    1341092300
5   1789    3   title   example title #3
6   1789    3   date    1341081200

这是我需要的结果:

uid formId  postId  name    value
3   1789    2   title   example title #2
4   1789    2   date    1341092300
1   1789    1   title   example title #1
2   1789    1   date    1341091600
5   1789    3   title   example title #3
6   1789    3   date    1341081200

结果按名称列中具有日期的值排序
(这些值只是示例)

编辑:这是一个 sqlfiddle:http ://sqlfiddle.com/#!2/0d3c32/2

4

3 回答 3

2

甚至这个问题也是极好的老问题。我想在此处保留有关如何对 EAV 执行数据排序的准确答案。

为了达到原题的预期,可以使用下面的 SQL 对指定的列进行排序。

SELECT mdata.uid, mdata.formId, mdata.postId, mdata.name, mdata.value
FROM formFields mdata
WHERE mdata.formId = '1789'
    AND mdata.deleted = 0
    AND mdata.hidden = 0
ORDER BY (
    SELECT s.value FROM formFields s 
    WHERE s.name='date' 
    AND s.postId=mdata.postId
) DESC

上面的 SQL 将产生以下结果。

uid formId  postId  name    value
3   1789    2   title   example title #2
4   1789    2   date    1341092300
1   1789    1   title   example title #1
2   1789    1   date    1341091600
5   1789    3   title   example title #3
6   1789    3   date    1341081200

希望这个答案有帮助。

于 2018-05-23T07:13:55.847 回答
1

如果你想要ORDER BY这个date值,那么你可以使用这样的东西:

SELECT
  formFields.uid,
  formFields.formId,
  formFields.postId,
  formFields.name,
  formFields.value 
  FROM formFields
INNER JOIN formFields aux 
  ON (aux.name = "date")
WHERE formFields.formId = "1789"
  AND formFields.deleted = 0
  AND formFields.hidden = 0
ORDER BY case when formFields.name = 'date' then 0 else 1 end 

请参阅带有演示的 SQL Fiddle

于 2012-10-15T11:32:40.220 回答
0
 SELECT     formFields.uid,     
      formFields.formId,     
      formFields.postId, 
      formFields.name,
     formFields.value 
 FROM formFields tx_gcgluteusfeed_formFields 
 INNER JOIN formFields b  
      ON formFields.postId = b.postId 
 INNER JOIN formFields c 
      ON (c.name = "date")  
 WHERE  ormFields.formId = "1789" 
      AND formFields.deleted = 0 
      AND formFields.hidden = 0 
 ORDER BY 1 DESC

如果你想按第一列排序

于 2012-10-15T10:06:18.987 回答