Get all data from 3 table in MySQL - mysql

I want to get all the data through the username from the 3 tables but I can not.
$username = $_GET['username'];
$res=$conn->query("select * from posts,tbl_view,tbl_user where posts.idpost=tbl_view.post_id AND
username='$username'");

Seems you missed the condition for join tbl_user with post.
Assuming your fk column is user_id, your query could be:
select *
from posts
INNER JOIN tbl_view ON posts.idpost=tbl_view.post_id
INNER JOIN tbl_user ON posts.user_id = tbl_user.id
WHERE tbl_user.username='$username'
You should not use the old join syntax based on comma separated table's name and where condition but use the explicit join syntax
And you should avoid the use of php var in sql. You should use prepared statement and parameter binding (to avoid SQL injection risk).

Related

Request SQL when table contains attributes composed by several words separated by point.

For a projet, I retrieved the database from a client. This database contains tables that have attributes composed by several words that are concatenated separated by a point. exemple :
table A : id, number.client , global.score
table B : id, favorite.style
So when I do a sql request on this tables to filter to filter the results according to number.client for exemple, I have an error returned by MySQL.
For exemple I have this request :
SELECT * FROM A
INNER JOIN B
ON (A.ref_track = B.id)
INNER JOIN C
ON (C.id = B.ref_plannode)
WHERE (B.id= 1)
AND (A.number.client > 50)
ORDER BY A.id DESC
When I run this request I get this error :
MySQL replied:
#1064 - Syntax error on A.number.client > 50
I think that MySql don't failed when we have an attribute composed by servel words separated by point ( like number.client). So what is the solution ??
For inforamtion this database is out of my responsibility, I got it from a client!!.
You have to quote the columns names with "`"
SELECT *
FROM A
JOIN B
ON A.ref_track = B.id
JOIN C
ON C.id = B.ref_plannode
WHERE B.id= 1
AND A.`number.client` > 50
ORDER BY A.id DESC
Edit
Working example
Is the same case that white spaces, you can use this:
SELECT * FROM A
INNER JOIN B
ON (A.ref_track = B.id)
INNER JOIN C
ON (C.id = B.ref_plannode)
WHERE (B.id= 1)
AND (A.`number.client` > 50)
ORDER BY A.id DESC
The MySQL can use diferent quotes or braquets, depends of configuration.
The MySQL server can operate in different SQL modes, and can apply these modes differently for different clients, depending on the value of the sql_mode system variable.
You can view the configuration with this command:
SELECT ##GLOBAL.sql_mode;
SELECT ##SESSION.sql_mode;
And you can know more about the configuration of mysql here https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi_quotes
Try to quote the column name putting it between square brackets.
So
AND (A.[number.client] > 50)

Converting int to varchar data type in MySQL

I have two tables. I need to compare two values but they are in different datatype in both the tables. In one table, it is int and in another table it is varchar. I tried using varchar with cast(), but cast() does not work with varchar.
My query is like following:
select user.username, user_follow.object_id from user,user_follow
left join user_follow
ON cast(user_follow.object_id as varchar(25))= user.username
WHERE user.username= cast(user_follow.object_id as varchar(25));
Help please.
thanks.
"does not work" is not a precise description of the observed behavior.
We expect MySQL to "work" according to the specification. The behavior we expect is for MySQL to return a specific error message, such as
Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near VARCHAR
We expect MySQL to return that error message because according to the MySQL Reference Manual, VARCHAR is not a valid type for CAST, but CHAR is a valid type.
Reference:
http://dev.mysql.com/doc/refman/5.7/en/cast-functions.html#function_convert
NOTE:
There are some other problems with the query.
There appear to be two references to the user_follow table. At least one of those references will need to have a table alias assigned.
The query is also using old-school comma syntax for a join operation, mixed with a join operation is using the newer JOIN keyword.
Without a specification of the resultset to be returned, we can only guess at which queries will satisfy the requirements.
SELECT u.username
, f.object_id
FROM user u
LEFT
JOIN user_follow f
ON CONVERT(CHAR(25),f.object_id) = u.username
You should cast as a CHAR datatype, there is no varchar datatype that you can cast data to, anyway try this please:)
Not sure what you want to use, left join or join.
select u.username, uf.object_id from user u
left join user_follow uf
ON cast(uf.object_id as char(25))= cast(u.username as char(25))
-- WHERE cast(u.username as char(25)) = cast(uf.object_id as char(25));
Or
select u.username, uf.object_id from user u, user_follow uf
-- left join user_follow uf
-- ON cast(uf.object_id as char(25))= cast(u.username as char(25))
WHERE cast(u.username as char(25)) = cast(uf.object_id as char(25));
And take a look of function_cast.
You can use CONCAT(user_follow.object_id)

MySQL Error You can't specify target table for update in FROM clause

I have a 2 tables MST_customer and TRN_sales in my database with corrupt entries. The next query returns the corrupt entries:
SELECT TRN_sales.cust_no
FROM MST_customer
RIGHT OUTER JOIN TRN_sales
ON MST_customer.cust_no = TRN_sales.cust_no
WHERE MST_customer.cust_name IS NULL;
I tried to delete them executing:
DELETE FROM mydbB.TRN_sales
WHERE TRN_sales.cust_no IN (
SELECT TRN_sales.cust_no
FROM MST_customer
RIGHT OUTER JOIN TRN_sales
ON MST_customer.cust_no = TRN_sales.cust_no
WHERE MST_customer.cust_name IS NULL
);
But I get the next error:
You can't specify target table 'TRN_sales' for update in FROM clause
How can I resolve this problem ?
To be a bit more on "the safe side" you should specifiy the table (here: alias name s) you want to delete from like:
DELETE s FROM TRN_sales s
LEFT JOIN MST_customers ON MST.cust_no=TRN.cust_no
WHERE MST.cust_name IS NULL;
Personnaly I believe, this LEFT JOIN is easier to read, although of course you can do the same with your RIGHT JOIN version.
Why you don't try below-
DELETE TRN.*
FROM MST_customer MST
RIGHT OUTER JOIN TRN_sales TRN
ON MST.cust_no = TRN.cust_no
WHERE MST.cust_name IS NULL;
Note: For safe side keep backup of both tables before executing this query.

MySql update syntax error from inner join

UPDATE
`universities`
SET
`universities`.countryid = `countries`.id,
FROM
`universities`
INNER JOIN
`countries`
ON
`universities`.country = `countries`.name
When I try to run the sql statements above via PhpMyAdmin, it would give syntax errors. I wrote the statements based on this answer.
This is the correct syntax in MySQL:
UPDATE universities u JOIN
countries c
ON u.country = c.name
SET u.countryid = c.id;
In addition, I introduced table aliases (so the query is easier to write and to read) and removed an extraneous comma.

Symfony2 - subquery within a join error

I would like to use a subquery inside a join, however Symfony2 throws the following error:
Here is my failed attempt:
$query = $em->createQuery(
'SELECT
sc.id AS id,
u.id AS userId,
u.username AS username,
sc_count.upvotes
FROM
myBundle:SuggestedCar sc
INNER JOIN myBundle:User u WITH sc.user_id = u.id
INNER JOIN ( SELECT sc1.user_id, COUNT(sc1.id) AS upvotes
FROM myBundle:SuggestedCar sc1
GROUP BY sc1.user_id
) sc_count WITH u.id = sc_count.user_id'
);
Basically I'm just joining 3 tables and the third one has a count. The query worked when executing it inside the database.
How would it be possible to use a SELECT statement inside a join? Is it a good idea to use raw SQL at this point?
The $em->createQuery() function is expecting DQL as the parameter, not SQL. If you want to execute a raw SQL statement, the syntax is different. You can do it like this:
$sql = "SELECT * FROM my_table";
$em = $this->getDoctrine()->getManager();
$stmt = $em->getConnection()->prepare($sql);
$stmt->execute();
$result = $stmt->fetchAll();
for more on DQL or querying for objects, see Querying for Object. The biggest difference is DQL will return an object (based on your entity classes in Symfony). The method I posted above will just give you a PDO result. So if you execute raw SQL, don't expect to be able to use the result as an object.
If you want to use raw SQL and still have the result mapped to an object, you can look at the doctrine docs about Result set mapping. In my opinion, this is more work than necessary.