mysql 2 join error on multiple WHERE clause - mysql

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');

Related

SUM inside SUM SQL Invalid use of group function

Hi I want to perform a calculation inside a SUM with my sql, but there is one SUM field that consist of other SUM fields. I get the General error: 1111 Invalid use of group function. What is the proper way of summing other sum fields in SQL?
I can't use the alias of other sum fields to perform the calculation because it says that the alias is unidentified.
This part is my problem
SUM((SUM(transactions.payable) + SUM(transactions.discount) ) - SUM(deliveries.delivery_fee) ) AS raw_sales
Thank you
Here is my SQL.
SELECT
MONTHNAME(transactions.date_transac) AS MONTH,
SUM(transactions.payable) AS total,
SUM(transactions.discount) AS discount,
SUM(deliveries.delivery_fee) AS delivery,
SUM(
(
SUM(transactions.payable) + SUM(transactions.discount)
) - SUM(deliveries.delivery_fee)
) AS raw_sales,
MONTH(transactions.date_transac) AS monthnum
FROM
`transactions`
LEFT JOIN `requisitions` ON `transactions`.`requisition_id` = `requisitions`.`id`
LEFT JOIN `transactions` AS `ct`
ON
`transactions`.`code` = `ct`.`charge_transaction_code`
LEFT JOIN `deliveries` ON `transactions`.`delivery_id` = `deliveries`.`id`
WHERE
`transactions`.`transaction_type` = Sale AND YEAR(`transactions`.`date_transac`) = 2020
GROUP BY
`month`
ORDER BY
`monthnum` ASC
enter image description here
You can't nest aggregate functions. Here, I suspect that you could move the arithmetics within the aggregate function rather than attempting to nest:
SUM(
transactions.payable
+ transactions.discount
- COALESCE(deliveries.delivery_fee, 0)
) AS raw_sales
delivery_fee comes from a left join table so it could be null, hence we use coalesce().
That said, I am quite suspicious about the logic of your query. I am wondering, for example, why transactions appears twice in the from clause. There are also missing quotes around literal string "Sale" in the WHERE clause. If you were to ask a legitimate question, including sample data, desired results, and an explanation of the purpose of the query, one might be able to suggests optimizations.
The query just worked, I haven't realized that it is no longer necessary to calculate all Sum fields. I just removed the external sum.

SQL Join ON clause valid referencing on aliases

I am generating an SQL query and I need to get the data from a JSON stored on a field of my table. It goes something like this
SELECT creation.INSERT_DATE as applicationDateTime,
REPLACE(json_extract(creation.FACILITY_DATA, '$.loanType'), '"', '') AS loanType,
lookup_detail.DETAIL_DESCRIPTION AS financingType
FROM creation
LEFT JOIN lookup_detail ON lookup_detail.DETAIL_CODE = loanType
So basically I am trying to get put a connection with tables creation and lookup_detail through field FACILITY_DATA which has JSON data and alias of loanType to reference against DETAIL_CODE field. However, I get this error
code:"ER_BAD_FIELD_ERROR"
errno:1054
sqlMessage:"Unknown column 'loanType' in 'on clause'"
sqlState:"42S22"
Is there anything I could do to work on this? I tried to search what are the valid reference to ON clause of JOIN operation, but I only get the typical ways.
Either repeat the expression in the ON clause, or join with a subquery.
SELECT c.applicationDateTime, c.loanType, l.financingType
FROM (
SELECT INSERT_DATE as applicationDateTime,
REPLACE(json_extract(creation.FACILITY_DATA, '$.loanType'), '"', '') AS loanType
FROM creation
) AS c
JOIN lookup_detail AS l ON l.DETAIL_CODE = c.loanType
Also, you probably should be using JSON_UNQUOTE() rather than REPLACE(). Or you can use the ->> operator, which extracts and unquotes in one step.

Error with inner join mysql query

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.)

Using the right MYSQL JOIN

I'm trying to get all the data from the match table, along with the currently signed up gamers of each type, experienced or not.
Gamers
(PK)Gamer_Id
Gamer_firstName,
Gamer_lastName,
Gamer experience(Y/N)
Gamer_matches
(PK)FK GamerId,
(PK)FK MatchId,
Gamer_score
Match
(PK)Match_Id,
ExperiencedGamers_needed,
InExperiencedGamers_needed
I've tried this query along with many others but it doesn't work, is it a bad join?
SELECT M.MatchId,M.ExperiencedGamers_needed,M.InExperiencedGamers_needed,
(SELECT COUNT(GM.GamerId)
FROM Gamers G, Gamers_matches GM
WHERE G.GamerId = GM.GamerId
AND G.experience = "Y"
AND GM.MatchId = M.MatchId
GROUP BY GM.MatchId)AS ExpertsSignedUp,
(SELECT COUNT(GM.GamerId)
FROM Gamers G, Gamers_matches GM
WHERE G.GamerId = GM.GamerId
AND G.experience = "N"
AND GM.MatchId = M.MatchId
GROUP BY GM.MatchId) AS NovicesSignedUp
FROM MATCHES M
What you've written is called a correlated subquery which forces SQL to re-execute the subquery for each row fetched from Matches. It can be made to work, but it's pretty inefficient. In some complex queries it may be necessary, but not in this case.
I would solve this query this way:
SELECT M.MatchId, M.ExperiencedGamers_needed,M.InExperiencedGamers_needed,
SUM(G.experience = 'Y') AS ExpertsSignedUp,
SUM(G.experience = 'N') AS NovicesSignedUp
FROM MATCHES M
LEFT OUTER JOIN (Gamer_matches GM
INNER JOIN Gamers G ON G.GamerId = GM.GamerId)
ON M.MatchId = GM.MatchId
GROUP BY M.MatchId;
Here it outputs only one row per Match because of the GROUP BY at the end.
There's no subquery to re-execute many times, it's just joining Matches to the respective rows in the other tables once. But I use an outer join in case a Match has zero players of eithe type signed up.
Then instead of using COUNT() I use a trick of MySQL and use SUM() with a boolean expression inside the SUM() function. Boolean expressions in MySQL always return 0 or 1. The SUM() of these is the same as the COUNT() where the expression returns true. This way I can get the "count" of both experts and novices only scanning the Gamers table once.
P.S. MySQL is working in a non-standard way to return 0 or 1 from a boolean expression. Standard ANSI SQL does not support this, nor do many other brands of RDBMS. Standardly, a boolean expression returns a boolean, not an integer.
But you can use a more verbose expression if you need to write standard SQL for portability:
SUM(CASE G.experience WHEN 'Y' THEN 1 WHEN 'N' THEN 0 END) AS ExpertsSignedUp

Multiple joins involving same table produces "column doesn't exist" error - MySQL

I'm new to joins and I'm sure this is ridiculously simple. If I remove one join in the query the remainder of the query works regardless of which join I remove. But as shown it gives the error saying the column doesn't exist. Any pointers?
select
loc_carr.address1 as carr_addr1,
loc_cust.address1 as cust_addr1
from db_name.carrier, db_name.customer
join db_name.location as loc_carr on vats.carrier.location_id=loc_carr.location_id
join db_name.location as loc_cust on vats.customer.location_id=loc_cust.location_id
thanks
I'll take a guess that there is a column named something like carrier_id that can be used to join the carrier and customer tables. Given that assumption, try this:
select
loc_carr.address1 as carr_addr1
, loc_cust.address1 as cust_addr1
from vats.carrier as a
join vats.customer as b
on b.carrier_id=a.carrier_id
join vats.location as loc_carr
on loc_carr.location_id=a.location_id
join vats.location as loc_cust
on loc_cust.location_id=b.location_id
Notice the use of aliases for the table references to make things easier to read. Also note how I'm using explicit SQL join syntax (instead of listing tables separated by commas).
#Bob Duell has the solution for your problem. To understand better why this error is produced, notice that in the FROM clause, you "join" tables using both explicit JOIN syntax and the implicit joins with comma: , which is (almost) equivalent to a CROSS JOIN. The precedence however of JOIN is stronger than the comma , operator. So, that part is parsed like this:
FROM
( db_name.carrier )
,
( ( db_name.customer
JOIN db_name.location AS loc_carr
ON carrier.location_id = loc_carr.location_id -- this line
) -- gives the error
JOIN join db_name.location AS loc_cust
ON customer.location_id = loc_cust.location_id
)
In the mentioned line above, the vats.carrier.location_id throws the error, as there is no carrier table in that scope (inside that parenthesis).