如何创建需要参数的视图?

时间:2017-08-14 04:46:28

标签: mysql sql view

这是我的表结构:

-- users
+----+--------+---------------------+----------+--------------------+
| id |  name  |       email         | password |      cookie        |
+----+--------+---------------------+----------+--------------------+
| 1  | Jack   | jack0011@gmail.com  | 098u23r8 | kj3409t34034u8rf   |
| 2  | Peter  | wanter_s@gmail.com  | k0io34r4 | m32i0949y834rf34   |
| 3  | Martin | dr.mrtn@yahoo.com   | fg345t34 | rf34r89p23r49i34   |
+----+--------+---------------------+----------+--------------------+

-- user_details
+---------+------+----------------------+----------------+
| user_id | age  |          about       |      date      |
+---------+------+----------------------+----------------+
| 1       | 32   | NULL                 | NULL           |
| 2       | NULL | A senior developer   | 1992-02-10     |
| 3       | 18   | NULL                 | 1999-01-06     |
+---------+------+----------------------+----------------+

现在我想像这样VIEW

Create View `user` as 
SELECT u.id, u.name, u.email
       ud.age, ud.about, ud.date
FROM users u
INNER JOIN user_details -- there is a trigger which makes a row in this table after insert in users table.
ON u.id = ud.user_id

现在我想为特定用户使用上面的VIEW。我可以这样做:

SELECT * FROM user WHERE id = :user_id

但我猜这是很多废物处理。无论如何,我怎样才能每次都将AND u.id = :user_id这样的东西附加到VIEW的逻辑上?

2 个答案:

答案 0 :(得分:0)

视图本身没有任何参数。但是,您可以使用select声明来过滤view中的数据,就像在其他任何select中一样:

select from `user` where id = :id

没有其他方法可以在视图中包含动态过滤。

答案 1 :(得分:0)

View不能有任何输入参数,因此你必须创建视图,然后你可以根据你想要的结果使用where条件来调用view作为select查询。例如: -

select from `user` where id = 1;
select from `user` where id in (1,2);