Order a table by another table column? - php

I have this query:
$q = "SELECT * FROM user
WHERE sec='1' AND reg_by='".$_SESSION['login_username']."'
ORDER BY date DESC LIMIT $startrow, 30 ";
I have another table which stores appointments, it has a column named meet.
How can I sort this query by meet?
Not all data at users are in other table.

You can use the below query. Replace another_table with your original table name :
$q = "SELECT u.* FROM user AS u LEFT JOIN another_table AS at ON u.userid = at.userid WHERE u.sec='1' AND u.reg_by='".$_SESSION['login_username']."' ORDER BY at.meet DESC LIMIT $startrow, 30 ";

you can use joining for this like
select user.*,meet.* from user left join meet on (meet.userid = user.id) where user.sec='1' AND user.reg_by='".$_SESSION['login_username']."' order by meet.userid DESC

$q = "SELECT * FROM user INNER JOIN user
ON meets.userid=user.userid WHERE sec='1' AND reg_by='".$_SESSION['login_username']."' ORDER BY date DESC LIMIT $startrow, 30 ";

Related

Search query involving two tables in mysql

I have two tables, users and sales. sales.userId = user.id
I am trying to use following query. To search parameters in both users and sales.
SELECT * FROM sales INNER JOIN users ON users.id = sales.userId WHERE 'users.fullname' like '%Cloud%' OR 'users.storename' like '%cloud%' order by sales.id DESC
No result is showing up. What could be wrong in query.
e.g one user['fullname'] is CloudBuck Abc
if(isset($_GET["q"]) && $_GET["q"]!="")
{
$q = trim($_GET["q"]);
$where = "WHERE users.fullname like '%".$q."%' OR users.storename like '%".$q."%'";
}
$query = "SELECT *
FROM sales
INNER JOIN users ON users.id = sales.userId ".$where." order by sales.id DESC";
You are quoting the field names and this is not allowed, either use backticks if its a reserved word or do not use it.
SELECT * FROM sales
INNER JOIN users ON users.id = sales.userId
WHERE `users`.`fullname` like '%Cloud%'
OR `users`.`storename` like '%cloud%'
order by sales.id DESC
SELECT * FROM sales INNER JOIN users ON users.id = sales.userId
WHERE (users.fullname like '%Cloud%' OR users.storename like '%cloud%')
order by sales.id DESC
Remove the single qoutes around the column names:
SELECT *
FROM sales
INNER JOIN users ON users.id = sales.userId
WHERE users.fullname like '%Cloud%' OR users.storename like '%cloud%' order by sales.id DESC
Because mysql will use it as string if the single quote is set.

Doctrine Order by id=1

I want get list users and current user must be first every-time.
In MySql i can make as:
SELECT * FROM `user` ORDER BY id = 2 DESC
In Doctrine i try make alike:
$query = $this->_em->createQuery("SELECT bul, u, c FROM 'Building\Entity\BuildingUserLink' bul JOIN bul.building b JOIN bul.company c JOIN bul.user u WHERE b = :building_id ORDER BY u.id = :current_id DESC");
$query->setParameters(array('building_id' => $building_id, 'current_id' => $current_id));
return $query->getResult();
But i get error - "Expected end of string, got \u0027=\u0027\"
What is my fault?
PS I used ZF2+DOctrine
SELECT * FROM `user` ORDER BY id = 2 DESC, id DESC
In your actual query:
ORDER BY u.id = :current_id DESC, u.id DESC
This can be done using the FIELD function in MySQL. Support for the FIELD function can be added to doctrine using https://github.com/beberlei/DoctrineExtensions.
The query would be:
SELECT * FROM `user` ORDER BY FIELD(id, 2) DESC

mysql Selecting from two different tables.

$sql = "select body, stamp from posts where user_id = '$userid' order by stamp desc";
NOTE: the above query works fine. What I want to do is also select username from my users table, and display the username that matches the user_id.
I have edited the above statement like so, and it doesnt work. Can someone suggest the correct query? My goal is to also be able to display usernames. in addition to simply displaying user_id.
$sql = "select body, stamp from posts AND username from users where user_id = '$userid' order by stamp desc";
My goal is to also be able to display usernames. instead of simply user_id.
You'll need to use a JOIN to bring the two tables together on the matching field, so something like:
$sql = "SELECT p.body, p.stamp, u.username FROM posts p INNER JOIN users u ON p.user_id=u.user_id WHERE p.user_id='$userid' ORDER BY p.stamp DESC";
You can use table name to select the columns. Ex:
$Query = "select table1.body, table1.stamp, users.username from posts, users where user_id = '$userid' order by stamp desc";
But, this method is not good in performance.
The best method is:
$Query = "SELECT table1.body, table1.stamp, users.username
FROM posts
INNER/LEFT/RIGHT JOIN users
ON users.user_id = '$userid' AND users.user_stamp = stamp.stamp_id
All the tables must be related.
Greetings,
$sql = "select body, stamp from posts , username from users where user_id = '$userid' order by stamp desc";
I just corrected the syntactical error in your query... that is the AND keyword should be replaced by ,.
$sql = "
select body, stamp from posts where user_id = '$userid' order by stamp desc
UNION ALL
select body, stamp from username where user_id = '$userid' order by stamp desc
";
http://dev.mysql.com/doc/refman/5.0/en/union.html
You should use aliases or table name to avoid the duplicate problem like this
tablename.column
or
alias.column
you can set the alias in your where clause :
FROM table as alias_name
$sql = "SELECT p.body,p.stamp,u.username from posts p LEFT JOIN users as u ON (p.user_id = u.user_id) WHERE user_id = '$user_id' ORDER BY p.stamp DESC";
should do it
Try this:
select body, stamp, username
from posts p JOIN users a ON p.user_id = a.user_id
WHERE p.user_id = '$userid' order by stamp desc
This should work fine:
SELECT posts.body, posts.stamp, users.username
FROM posts, users
WHERE posts.user_id = '$userid' AND posts.user_id = users.user_id
ORDER BY posts.stamp DESC
select body, stamp, username
from posts,users
where users.user_id = post.user_id
and users.user_id = '$userid'
order by stamp desc;

Multiple tables and queries

How do I join something like this together:
$query = ("SELECT * FROM profiles,follow
WHERE follow.friend ='$user'
AND follow.user !='$user'
AND profiles.user1 =follow.user
ORDER BY id DESC limit 20");
or
("SELECT * FROM profiles WHERE user1='$user'");
I need the query to display two different things how do I do that.
This one?
SELECT
*
FROM
follows
INNER JOIN
profiles
ON (profiles.user1 = follow.user)
WHERE
follow.friend = '{$user}'
AND follow.user != '{$user}'
AND profiles.user1 = '{$user}'
ORDER BY
profiles.id DESC
LIMIT 20
Use UNION:
SELECT *
FROM profiles, follow
WHERE follow.friend ='$user'
AND follow.user !='$user'
AND profiles.user1 =follow.user
ORDER BY id DESC limit 20
UNION
SELECT *
FROM profiles
WHERE user1='$user'
try this
$query = "SELECT * FROM profiles,follow WHERE follow.friend ='$user' and follow.user !='$user' and profiles.user1 =follow.user and profiles.user1='$user' order by id DESC limit 20";

PHP script to list total posts by users

I have a database with two tables, Users and Posts. I'd like to write a php script to list, in order, the top 20 usernames with the number of posts they've made. The username field is cUsername in the Users table. The Users table intUserID field and the Posts table's intPosterID field correspond to eachother.
Any help would be much appreciated. Thanks!
Use GROUP BY and count. This will get you a list of user IDs to their counts:
SELECT intPosterId, COUNT(*)
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20
You can use the result in a subquery:
SELECT u.cUsername, pcnt.postCount
FROM Users AS u
INNER JOIN (
SELECT intPosterId, COUNT(*) as postCount
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20
) AS pcnt
ON u.intUserId = pcnt.intPosterId
To use it in a PHP script:
<?php
$sql = '
SELECT u.cUsername, pcnt.postCount
FROM Users AS u
INNER JOIN (
SELECT intPosterId, COUNT(*) as postCount
FROM Posts
GROUP BY intPosterId
ORDER BY COUNT(*) DESC
LIMIT 20
) AS pcnt
ON u.intUserId = pcnt.intPosterId
';
$pdo = new PDO(
'mysql:host=your_host;dbname=your_db',
'username',
'password',
array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION)
);
$stmt = $pdo->prepare($sql);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "{$row['cUsername']}: {$row['postCount']} <br />\n";
}

Categories