Error with inner join mysql query - mysql

Please help with inner join error. I was done this query in MS ACCESS - it's work, but when it in phpmyadmin or cmd - error
SELECT zakaz.c_id, Count(zakaz.c_id) AS [counter]
FROM country JOIN ((resort JOIN hotel ON resort.res_id = hotel.res_id)
JOIN ([number] JOIN zakaz ON (number.[num_id] = zakaz.[num_id])
AND (number.[num_id] = zakaz.[cost])) ON hotel.h_id = number.[h_id])
ON country.c_id = resort.c_id GROUP BY zakaz.c_id;

In MySQL, the square brackets ([ ]) are not valid characters for an identifier.
In Access, those are used to enclose an identifier. In MySQL, we use backtick characters to enclose an identifier that needs to be escaped. (This allows us to include spaces or other characters which are not normally allowed in an identifier, and allows us to use reserved words as identifiers. In your query, none of the identifiers need to escaped in backticks.
Also, in MySQL, those parens aren't necessary.
The query could be expressed in a form that is easier for the human reader to decipher. For example:
SELECT zakaz.c_id
, COUNT(zakaz.c_id) AS `counter`
FROM country
JOIN resort
ON resort.c_id = country.c_id
JOIN hotel
ON hotel.res_id = resort.res_id
JOIN number
ON number.h_id = hotel.h_id
JOIN zakaz
ON zakaz.num_id = number.num_id
AND zakaz.cost = number.num_id
GROUP BY zakaz.c_id
(It's bit of an odd condition that zakaz.cost needs to be equal to number.num_id, as well as zakaz.num_id... that appears to be the condition specified in the original query.)

Related

In mysql, can ON statement in an INNER JOIN accept an OR clause?

Can an ON clause of an INNER JOIN accept an AND?
In the following (and presently working) mysql example:
SELECT p.pk_ProductID
FROM Product p
INNER JOIN SerialNumber sn
ON sn.fk_ProductID = p.pk_ProductID
WHERE sn.pk_SerialNumberID = %s AND p.ProductGUID = %s
LIMIT 1
Is it legit to add an OR clause with sn.fk_ProductID2 like so:
ON sn.fk_ProductID = p.pk_ProductID OR sn.fk_ProductID2 = p.pk_ProductID
If legit, would it be stylistically more readable to be in parenthesis:
ON (sn.fk_ProductID = p.pk_ProductID) OR (sn.fk_ProductID2 = p.pk_ProductID)
NOTE: I have reviewed several seemingly similar questions on SO which contained conflicting advice re part 1 of my question.
It's legal to write a query like you show. The expression following the ON keyword can be any boolean expression. Strictly speaking, it doesn't even have to reference either table you are joining.
It is not necessary to use parentheses, because the operator precedence of = versus OR is clearly that = binds tighter. See https://dev.mysql.com/doc/refman/8.0/en/operator-precedence.html for details on that.

Syntax error in complex SQL Query condition

I am having some trouble with my sql statement.
Here is a picture of the relevant tables:
A product can be in multiple categories.
A single product can have multiple varietycategories (ie: size, color, etc)
a varietycategory can have multiple varietycategoryoptions (ie: small, medium, large)
the table searchcriteria.criterianame loosly relates to varietycategory.category
the table searchcriteriaoption.criteriaoption loosely relates to varietycategoryoption.descriptor.
I get the searchcriteria.criterianame and use that string as the value we want to match with varietycategory.category and we also have to get the various searchcriteriaoption.criteriaoption strings (for that searchcriteria.criterianame) and match that against varietycategoryoption.descriptor for that varietycategory.category.
Here is the sql:
SELECT DISTINCT categories.*, product.*
FROM (categories, product, product_category)
LEFT JOIN varietycategory ON varietycategory.productid = product.id
LEFT JOIN varietycategoryoption ON varietycategoryoption.varietycategoryid = varietycategory.id
WHERE product_category.categoryid=4
AND product.id=product_category.productid
AND categories.category_id=product_category.categoryid
AND (
(varietycategory.category = 'color' AND (varietycategoryoption.descriptor='red' OR varietycategoryoption.descriptor='blue'))
OR
(varietycategory.category = 'size' AND (varietycategoryoption.descriptor = 'small' OR varietycategoryoption.descriptor='medium'))
)
but I get an error:
Unknown column 'varietycategory.id' in 'on clause'
I have tried to figure out what I am doing wrong. I tried simplifying the query a bit (just to try and determine what part of the sql query was causing the problem) to only match the searchcriteria.category string with the varietycategory.category and the query returns the data set correctly.
Here is the working query (this query is simplified and insufficient):
SELECT DISTINCT categories.*, product.*
FROM (categories, product, product_category)
LEFT JOIN varietycategory ON varietycategory.productid = product.id
WHERE product_category.categoryid=4
AND product.id=product_category.productid
AND categories.category_id=product_category.categoryid
AND (varietycategory.category = 'color' OR varietycategory.category = 'size' OR varietycategory.category='shape');
But I also need to be able to match against the varietycategoryoptions as well.
Just to avoid confusion, I am only using searchcriteria to get the field category and use it as a string to match against the varietycategory.category
and I am only using searchcriteriaoption to get the field criteriaoption and use it as a string to match against varietycategoryoption.descriptor
Does anyone know what I am doing wrong with my 1st query?
Please do help as SQL is not expertise.
Thank you!
The error is at:
OR
(varietycategory.category = 'size' (varietycategoryoption.desciptor = 'small' OR varietycategoryoption.descriptor='medium'))
^
|
An operator (AND, OR) is missing here
This has nothing to do with the join syntax, by the way.
Do not mix implicit and explicit joins. Your query should look like:
SELECT DISTINCT c.*, p.*
FROM product_category pc join
categories c
on c.category_id = pc.categoryid join
product p
on p.id = pc.productid join
varietycategory vc
ON vc.productid = p.id
WHERE c.categoryid = 4 AND
vc.category in ('color', 'size', 'shape');
You probably don't need the distinct, but that depends on the data. The left join is unnecessary because you are filtering on the second table in the where.
A simple rule: Never use commas in the from clause. To help, MySQL has scoping rules that can cause queries to break when you mix implicit and explicit join syntax.
The problem was a misspelled field on the table varietycategory, which I named
vcid, when I almost always name my table primary key id's "id".

mysql 2 join error on multiple WHERE clause

I am trying to call specific information from my SQL table using the following statement
SELECT `PROP_STREET`, `PROP_PRICE`, `PROP_STATUS`, `AGT_FNAME`, `AGT_LNAME`
FROM `property`, `agent`
WHERE property.PROP_AGENT = agent.AGT_FNAME && property.PROP_STATUS = ("SOLD" , "Available for sale", "Under Contract");
As you can see, I am trying to call everything that is listed as SOLD, Available for sale and Under Contract. While I try to do this, I am getting an error operand should contain 1 coulmn this only happens when I am trying to call more than 1 PROP_STATUS
This is proper syntax for what you're trying to do:
select prop_street, prop_price, prop_status, agt_fname, agt_lname
from property p
join agent a
on p.prop_agent = a.agt_fname
where p.prop_status in ('SOLD', 'Available for sale', 'Under Contract')
Some notes:
Join conditions belong in the JOIN clause, not the WHERE clause. Although there is no functional difference, it is good practice.
&& does mean "AND" in other languages, but not SQL. Have to use "and"
Use single quotes for literals ('), not double quotes (")
Use IN, not =, when specifying more than one literal.
Avoid using old JOIN syntax(where clause) and use the newer join (with ON Clause).
SELECT `PROP_STREET`, `PROP_PRICE`, `PROP_STATUS`, `AGT_FNAME`, `AGT_LNAME`
FROM `property` INNER JOIN `agent`
ON property.PROP_AGENT = agent.AGT_FNAME
WHERE property.PROP_STATUS IN ('SOLD' , 'Available for sale', 'Under Contract');

LEFT JOIN query MYSQL does not work

I have 2 tables rtz_order and rtz_restaurant
From order I want purchaseprice from restaurant i want "restaurant_commission" both have a column called restaurant_id So i want to join these to tables and add the restaurant_commission tot the query. I have come up with this (the date part etc works, i was already using that but the query does not work since I added the join)
$sql = 'SELECT
order.orderpurchase,
order.orderdate,
order.status,
order.restaurant_id,
res.restaurant_commission,
res.restaurant_id
FROM rt_order order
LEFT JOIN rt_restaurant res ON order.restaurant_id = res.restaurant_id
WHERE date(order.orderdate) >= date(?) AND date(order.orderdate) <= date(?)
AND order.restaurant_id = ? AND order.status = "completed"';
I have tried diffrent things but i do not see why this is going wrong
ORDER is a reserved keyword.
Use backtics like:
`ORDER`
Check the complete list of reserved keywords here.
NOTE : It is better to avoid reserved keywords for column names, but if you use then wrap them with backtics.
Your alias order is a MySQL reserved word.
Make it either `order` using backticks, or change the alias' name.

Test for field length in MySql statement

I am using this part of a sql statement to delete accounts with the specific phone number in a cronjob.php file. How do I alter this statement to test for the length of a specific given field in the user-profies, rather than what I list here as the value being LIKE '%2147483648%'
$strSQL = "DELETE
FROM users,
profile_values
USING profile_values
INNER JOIN users USING(uid)
INNER JOIN profile_fields USING(fid)
WHERE profile_values.uid=users.uid
AND profile_values.value LIKE '%2147483648%'
AND (profile_fields.name = 'profile_phone_number')";
execSQL($strSQL);
If you are testing for length of the data in the field, you can use code like:
... WHERE LENGTH(TRIM(profile_values.value)) = 10 ...
substituting the correct field name. The TRIM function is important to eliminate any leading or trailing spaces which might have crept in to the data.
Be careful using a function like this to automatically delete users. It will be quite indiscriminate.