0

我从我的 php 类 2 个不同的方法中检索到 2 个 mysql 查询,它们看起来如下

 SELECT
domains.id,  domains.name, domains.meta_title,
domains.meta_keywords,  domains.meta_description,
produkt_modul.keywords, produkt_modul.program_id,produkt_modul.title, produkt_modul.items, produkt_modul.search_type
 FROM domains
 JOIN produkt_modul ON domains.id = produkt_modul.domains_id WHERE domains.name='$domain_name' ORDER BY position

正在为我的产品模块和第二个模块获取行

SELECT
domains.id, text_module.position, text_module.title, text_module.text
FROM    domains
JOIN    text_module
ON  domains.id = text_module.domains_id
WHERE   domains.name='$domain_name' AND active= 1 ORDER BY position

应该给我文本模块的行。

当我在视图中生成行的 html 输出时,我想在位置值之后订购主题。

例如应该是什么样子:

text_modul pos1
prod_modul pos2
prod_modul pos3
text_modul pos4

行的实际视图看起来

text_modul1
text_modul4
prod_modul2
prod_modul3

如何以正确顺序获取主题的方式获取行。

4

2 回答 2

0

目前尚不清楚该position列的来源,但我猜produkt_moduleandtext_module表都有一个position列。

要在 SQL 中执行此操作,您可以使用 UNION 并对组合结果进行排序。限制是联合在一起的两个结果必须具有相同数量的列,并且列必须是兼容的类型:

SELECT title, position FROM (
  SELECT p.title, p.position
  FROM produkt_module p
  JOIN domains d ON d.id = p.domains_id
  WHERE d.name = '$domain_name'
    UNION
  SELECT t.title, t.position
  FROM text_module t
  JOIN domains d ON d.id = t.domains_id
  WHERE d.name = '$domain_name'
  AND t.active
) ORDER BY position;

您还可以将两个结果集读入一个数组并在 PHP 中对其进行排序。

于 2012-05-11T05:52:20.047 回答
0

以下是如何在 PHP 中执行此操作。请注意,此代码假定position在两者produkt_moduletext_module结果中都是唯一的。

$allrows = array();
$res = mysql_query(/* your first query on produkt_module */);
while ($row = mysql_fetch_assoc($res) {
    $row['type'] = 'p';
    $allrows[$row['position']] = $row;
}

$res = mysql_query(/* your second query on text_module */);
while ($row = mysql_fetch_assoc($res) {
    $row['type'] = 't';
    $allrows[$row['position']] = $row;
}

ksort($allrows);  // sort all rows by position

foreach ($allrows as $pos => $row) {
    if ($row['type'] == 'p') {
        /* display a produkt_module row, i.e $row['title'], etc. */
    } elseif ($row['type'] == 't') {
        /* display a text_module row */
    }
}
于 2012-05-11T06:28:46.137 回答