select union with union table sql query

时间:2016-07-06 23:36:20

标签: php sql sql-server

我正在进行搜索分页,我试图使用union从三个表中选择计数但是我得到这样的错误 Fatal error: Cannot pass parameter 2 by reference in /home/plooks/public_html/user/test.php on line 106here is my table structure

表1名称>>博文

| bid   | title     | body          | author    |
|-----  |-------    |-------------  |--------   |
| 1     | new       | hello new     | you       |
| 2     | cast      | broadcast     | me        |
| 3     | hack      | who hack us   | you       |

table2 name>> forumnew

| fid   | ftitle    | fbody         | user  |

|-----  |-------    |-------------  |--------   |
| 1     | new forum | hello new     | you       |
| 2     | cast me   | broadcast     | me        |
| 3     | hack you  | who hack him  | us        |

table3名称>>下载

| did   | file      | disc          | type      |

|-----  |-------    |-------------  |--------   |
| 1     | whoweare  | hello new     | php       |
| 2     | cast      | broadcast     | html      |
| 3     | hack      | who hack us   | c++       |

SQL QUERY

SELECT COUNT(id) FROM (
    SELECT 'post' AS type, BID AS id FROM blogpost
    UNION
    SELECT 'jail' AS type, jid AS id FROM forumnew
    UNION
    SELECT 'article' AS type, TID AS id FROM download
)csl WHERE title LIKE :search OR title LIKE :search")

1 个答案:

答案 0 :(得分:1)

查询中存在错误,临时表title中没有csl,因此无法在WHERE子句中使用它。第二个OR title LIKE :search也是多余的。如果您不想对id进行 distinct 计数,那么您不需要其他列,只需要过滤标题列,结果将是相同的。

SELECT COUNT(*) FROM (
    SELECT title FROM blogpost
    UNION
    SELECT ftitle AS title FROM forumnew
    UNION
    SELECT disc AS title FROM download
) csl WHERE title LIKE :search

SELECT
  (SELECT COUNT(*) FROM blogpost WHERE title LIKE :search) +
  (SELECT COUNT(*) FROM forumnew WHERE ftitle LIKE :search) +
  (SELECT COUNT(*) FROM download WHERE disc LIKE :search)